The 3Sum Smaller coding problem asks you to count the number of index triplets such that and . Unlike other 3Sum variations, you don't need the actual triplets—just the total count of combinations that satisfy the inequality.
Asked by Microsoft and Oracle, this problem tests a candidate's ability to use the properties of a sorted array to count multiple solutions at once. It’s an exercise in efficiency; if you find one valid boundary, you can mathematically infer many other valid solutions without iterating through them.
This problem utilizes the Two Pointers interview pattern on a sorted array. The key insight is: if , then all elements between left and right will also satisfy the condition when paired with nums[i] and nums[left]. This allows you to add (right - left) to your count in time.
Array: [-2, 0, 1, 3], target = 2.
-2**: left = 0, right = 3.-2 + 0 + 3 = 1.left (0) and right (3) work. This includes and .Look for "counting" problems where you can avoid an inner loop by using the distance between two pointers. This "sliding window count" logic is a very common optimization in competitive programming.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Heaters | Medium | Solve | |
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve | |
| Friends Of Appropriate Ages | Medium | Solve | |
| Count the Number of Fair Pairs | Medium | Solve | |
| The Latest Time to Catch a Bus | Medium | Solve |