3Sum Smaller

medium array two pointers sorting

Problem

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

Inputnums = [-2,0,1,3], target = 2
Output2
Triplets (-2,0,1) and (-2,0,3) both sum to less than 2.

def three_sum_smaller(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
function threeSumSmaller(nums, target) {
  nums.sort((a, b) => a - b);
  let count = 0;
  for (let i = 0; i < nums.length - 2; i++) {
    let j = i + 1, k = nums.length - 1;
    while (j < k) {
      if (nums[i] + nums[j] + nums[k] < target) {
        count += k - j;
        j++;
      } else {
        k--;
      }
    }
  }
  return count;
}
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 j = i + 1, k = nums.length - 1;
            while (j < k) {
                if (nums[i] + nums[j] + nums[k] < target) {
                    count += k - j; j++;
                } else k--;
            }
        }
        return count;
    }
}
int threeSumSmaller(vector& nums, int target) {
    sort(nums.begin(), nums.end());
    int count = 0;
    for (int i = 0; i + 2 < (int)nums.size(); i++) {
        int j = i + 1, k = (int)nums.size() - 1;
        while (j < k) {
            if (nums[i] + nums[j] + nums[k] < target) { count += k - j; j++; }
            else k--;
        }
    }
    return count;
}
Time: O(n^2) Space: O(1)