bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 16. 3Sum Closest

16. 3Sum Closest

Leetcode Solutions

Approach: Two Pointers

  1. Initialize the closest sum closest to infinity.
  2. Sort the input array nums.
  3. Loop through the array with index i from 0 to n - 3:
    • Initialize two pointers, left to i + 1 and right to n - 1.
    • While left is less than right:
      • Calculate the current sum currentSum as nums[i] + nums[left] + nums[right].
      • If currentSum is equal to target, return currentSum immediately as it is the closest possible sum.
      • If the absolute difference between currentSum and target is less than the absolute difference between closest and target, update closest to currentSum.
      • If currentSum is less than target, increment left.
      • Otherwise, decrement right.
  4. Return closest after the loop ends.
UML Thumbnail

Approach: Binary Search

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...