3Sum Smaller Problem
#259
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 259.
Given an array of n integers nums and an integer 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.
Example 1:
Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]
Example 2:
Input: nums = [], target = 0
Output: 0
Example 3:
Input: nums = [0], target = 0
Output: 0
Constraints:
n == nums.length0 <= n <= 3500-100 <= nums[i] <= 100-100 <= target <= 100- The input is generated such that the answer is less than or equal to 10^9.
Solution
Approach: Sort + Two Pointers
We count index triplets, but a triplet's sum does not depend on the order of the indices, so we can sort the array first: the count stays the same.
Then fix the smallest element nums[i] and look for pairs j < k after it with nums[i] + nums[j] + nums[k] < target. Start with j = i + 1 and k at the end:
- If the sum is less than
target, then replacingkby any index fromj + 1tokonly makes the sum smaller. So allk - jpairs(j, j+1), ...,(j, k)work. Addk - jand movejright. - Otherwise
nums[k]is too large to pair withnums[j], or with anything bigger, so movekleft.
This counts pairs in batches instead of one by one, which is what makes it O(n2) instead of O(n3).
Complexity: O(n2) time and O(log n) extra space for sorting.
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
count = 0
for i in range(n - 2):
j, k = i + 1, n - 1
while j < k:
if nums[i] + nums[j] + nums[k] < target:
# With nums[i] and nums[j], every third value in nums[j+1..k] is small enough.
count += k - j
j += 1
else:
k -= 1 # nums[k] is too big for any j, drop it
return count