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.

Examples

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

Solution

Method 1 - Sorting and two pointer technique

The problem can be solved efficiently using the following approach:

  1. Sort the Array: Sorting helps simplify the process of finding valid triplets.
  2. Two-pointer Technique: For each element, use two pointers to find pairs whose sum with the current element is less than the target.

Code

Java
public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int count = 0;

        for (int i = 0; i < n - 2; i++) {
            int j = i + 1, k = n - 1;
            while (j < k) {
                if (nums[i] + nums[j] + nums[k] < target) {
                    count += k - j;
                    j++;
                } else {
                    k--;
                }
            }
        }

        return count;
    }
}
Python
class Solution:
    def threeSumSmaller(self, nums, target):
        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:
                    count += k - j
                    j += 1
                else:
                    k -= 1

        return count

Complexity

  • ⏰ Time complexity: O(n^2), since we use a nested loop with two pointers for each element.
  • 🧺 Space complexity: O(1), as we only use a constant amount of extra space aside from the input array.