Reference: LeetCode
Difficulty: Medium

My Post: [Java] It’s Easy Because It Allows Duplicate Results!

Problem

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

Note: We also count the duplicate pairs!

Example:

1
2
3
4
5
Input: nums = [-2,0,1,3], and target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]

Follow up: Could you solve it in $O(N^2)$ runtime?

Analysis

Two Pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int threeSumSmaller(int[] nums, int target) {
int n = nums.length;
Arrays.sort(nums); // sort
int count = 0;
for (int i = 0; i < n; ++i) {
// two pointers
int j = i + 1, k = n - 1;
int t = target - nums[i];
while (j < k) { // each element is only used once
if (nums[j] + nums[k] < t) {
// 0 1 2 3 4 <- index
// 1 2 3 4 5
// i j k <- say we have a valid pair [1, 2, 5]
// we have [1 2 5], [1 2 4], [1 2 3]. The count equals k - j
count += (k - j);
++j;
} else { // nums[j] + nums[k] >= t
--k;
}
}
}
return count;
}

Time: $O(N^2)$
Space: $O(1)$


Comment