LeetCode 16: 3Sum Closest Solution

Master LeetCode problem 16 (3Sum Closest), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

16. 3Sum Closest

Problem Explanation

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)

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 16 (3Sum Closest)?

This page provides optimized solutions for LeetCode problem 16 (3Sum Closest) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 16 (3Sum Closest)?

The time complexity for LeetCode 16 (3Sum Closest) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 16 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 16 in Java, C++, or Python.

Back to LeetCode Solutions