The Number of Subsequences That Satisfy the Given Sum Condition problem asks you to count non-empty subsequences of an array where min(subsequence) + max(subsequence) ≤ target. Since subsequences can pick any elements, sorting doesn't change which valid subsequences exist (only which element is min/max). This coding problem uses a two-pointer approach after sorting.
Microsoft, Meta, Amazon, Google, and Bloomberg ask this because the key insight — sorting preserves validity while allowing two-pointer pairing of min and max — is non-obvious. Once sorted, fixing the minimum (left pointer) and finding the rightmost valid maximum (right pointer) lets you count all valid subsequences between them in O(1) using powers of 2. The array, sorting, two pointers, and binary search interview pattern is the core.
Sort + two pointers + precomputed powers of 2. Sort the array. Two pointers: left = 0, right = n-1. While left ≤ right: if arr[left] + arr[right] ≤ target, all 2^(right-left) subsequences with arr[left] as minimum are valid (any subset of elements between them). Add to count. Advance left. Otherwise, decrement right. Precompute pow2 mod 10^9+7.
arr=[3,5,6,7], target=9. Sort: [3,5,6,7].
pow(2, k, mod) per iteration is slow).right - left elements can be chosen freely (not right-left+1).Two-pointer problems where sorting doesn't invalidate the solution are a common interview pattern. After sorting, fix one pointer (min) and find the farthest valid partner (max) using the other pointer. The count of subsequences between them is a power of 2. Precompute all needed powers of 2 up to n before the two-pointer loop. Practice "count subsequences with min+max ≤ target" variants with different constraints to build this intuition.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count the Number of Fair Pairs | Medium | Solve | |
| Friends Of Appropriate Ages | Medium | Solve | |
| Successful Pairs of Spells and Potions | Medium | Solve | |
| The Latest Time to Catch a Bus | Medium | Solve | |
| Heaters | Medium | Solve |