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.
259. 3Sum Smaller
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.
- Sort the array in non-decreasing order.
- Initialize a count variable to 0.
- Iterate over the array with a fixed index
iand use two pointersleftandrightto find the pairs that sum up to less than the target. - 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.
- Increment the count by
right - leftand move the left pointer to the right. - If the sum is greater than or equal to the target, decrement the right pointer.
- Repeat steps 4-6 until the left pointer crosses the right pointer.
- 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.