3 Sum Smaller

By | January 24, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

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.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. 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(n2) runtime?

Solution. This problem is similar to Number of Triangle. Let’s see we have i, j fixed. As long as nums[i] + nums[j] + nums[k] < target, then all set of (i, j, j + 1), (i, j, j + 2),…, (i, j, k – 1), (i, j, k) are qualified.

By this characteristic, We use i for outer loop from 0 to n – 1. For each loop, we set a left = ┬án + 1, right = n – 1. When sum less than target, we accumulate result and left++. Or we do right–.

Check my code on github: link