Thursday, July 29, 2021

3Sum Smaller

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.
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]

Approach:
Again this problem is similar to the previous 3Sum and 3Sum Closest problems. This problem also can be solved using the Two pointers method. Let's illustrate,
Now how can we move our pointers right? see, if the current sum is less than the target that means from right pointer to left pointer all will be included in our answer because they are all smaller than the target because they are already in sorted order. So if the current sum is smaller than the target then we will move our left pointer forward otherwise we will decrease the right pointer. See the code for a better understanding.



No comments:

Post a Comment