The "Count Pairs Whose Sum is Less than Target interview question" is a fundamental array optimization task. You are given an array of integers and a target. You need to find the number of pairs such that and nums[i] + nums[j] < target. This problem tests your ability to move beyond brute-force counting and utilize sorting to improve performance.
Companies like Meta and Amazon use the "Count Pairs Whose Sum is Less than Target coding problem" to assess a candidate's understanding of the "Two Pointers interview pattern." It evaluates the ability to recognize that sorting the array doesn't change the set of possible pairs but allows for a much more efficient search strategy ( vs ).
This problem is solved using the Sorting and Two Pointers pattern.
left = 0 and right = n - 1.nums[left] + nums[right] < target, then because the array is sorted, every element between left and right will also satisfy the condition when paired with nums[left]. There are right - left such pairs. Add this to your count and increment left.nums[left] + nums[right] >= target, then nums[right] is too large to pair with any element. Decrement right.Array: [-1, 1, 2, 3, 1], Target: 2
[-1, 1, 1, 2, 3].left=0 (-1), right=4 (3): Sum = 2. Not < 2. right--.left=0 (-1), right=3 (2): Sum = 1. < 2. Pairs: (-1, 1), (-1, 1), (-1, 2). Total += 3. left++.left=1 (1), right=3 (2): Sum = 3. Not < 2. right--.
... Result: 3.while loop instead of adding right - left. This loses the efficiency of the two-pointer pass.strictly less than target, not less than or equal to.Master the "Two Pointers" technique for inequalities. Whenever you need to count pairs based on a sum, sorting the array usually unlocks a linear or solution.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Distance Value Between Two Arrays | Easy | Solve | |
| Two Sum Less Than K | Easy | Solve | |
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve | |
| The Latest Time to Catch a Bus | Medium | Solve | |
| Count the Number of Fair Pairs | Medium | Solve |