16. 3Sum Closest

Explanation:

To solve this problem, we can follow these steps:

  1. Sort the input array nums.
  2. Initialize a variable closestSum to store the closest sum found so far.
  3. Iterate over the array nums up to the third last element.
  4. Inside the loop, use two pointers left and right to find the other two numbers for the current number.
  5. Calculate the current sum of the three numbers and update closestSum if the current sum is closer to the target.
  6. Update the pointers based on whether the current sum is less than or greater than the target.
  7. Continue iterating until all possible combinations are checked.

Time complexity: O(n^2) where n is the length of the input array nums. Space complexity: O(1)

import java.util.Arrays;

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closestSum = nums[0] + nums[1] + nums[2];

        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (Math.abs(sum - target) < Math.abs(closestSum - target)) {
                    closestSum = sum;
                }
                if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }

        return closestSum;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.