Back to Dashboard
3 Sum Smaller
MediumProblem Statement
Given an integer array nums and an integer target, return the number of triplets (i, j, k) such that 0 <= i < j < k < n and nums[i] + nums[j] + nums[k] < target.
Examples
Example 1:
- Input:
nums = [-2,0,1,3],target = 2 - Output:
2
Approach 1: Two Pointers
O(n^2)
O(1)
// The greatest will be either in the first or at the end, so we will fill it from the end.
class Solution {
public int searchTriplets(int[] arr, int target) {
var count = 0;
Arrays.sort(arr);
for (int i = 0; i < arr.length; i ++) {
var targetSum = target - arr[i];
var l = i + 1;
var r = arr.length - 1;
while (l < r) {
if (arr[l] + arr[r] < targetSum) {
count += (r - l);
l ++;
} else {
r --;
}
}
}
return count;
}
}