LeetCode 259: 3Sum Smaller Solution

Master LeetCode problem 259 (3Sum Smaller), 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.

Problem Explanation

Explanation:

This problem asks us to find the number of triplets in an array whose sum is less than a given target. We can solve this problem using a two-pointer approach.

  1. Sort the array in non-decreasing order.
  2. Initialize a count variable to 0.
  3. Iterate over the array with a fixed index i and use two pointers left and right to find the pairs that sum up to less than the target.
  4. If the sum of nums[i] + nums[left] + nums[right] is less than the target, then all the numbers between left and right form valid pairs as well.
  5. Increment the count by right - left and move the left pointer to the right.
  6. If the sum is greater than or equal to the target, decrement the right pointer.
  7. Repeat steps 4-6 until the left pointer crosses the right pointer.
  8. Return the final count.

: :

Solution Code

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int count = 0;
        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 (sum < target) {
                    count += right - left;
                    left++;
                } else {
                    right--;
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 259 (3Sum Smaller)?

This page provides optimized solutions for LeetCode problem 259 (3Sum Smaller) 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 259 (3Sum Smaller)?

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

Can I run code for LeetCode 259 on DevExCode?

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

Back to LeetCode Solutions