Number of Subsequences That Satisfy the Given Sum Condition (LeetCode 1498): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Sorting

Count the non-empty subsequences whose smallest plus largest element is at most target, modulo 10^9 + 7.

Intuition

Only the min and the max of a subsequence matter, and neither depends on element order. Sorting the array therefore does not change the answer, and after sorting a chosen set's min is its leftmost pick and its max is its rightmost pick.

Fix the min at sorted index left. The max can be any element up to the last index right where nums[left] + nums[right] still fits. Every element after left and up to right can be in or out on its own, so there are 2^(right - left) subsequences with that min.

As left grows, the min grows, so the largest allowed max can only shrink. That is the two pointer pattern: right only ever moves left, and each pointer crosses the array once.

Approach: Sort + two pointers + precomputed powers of two

  1. Sort nums.
  2. Precompute pow2[k] = 2^k mod 10^9 + 7 for k from 0 to n - 1.
  3. Set left = 0, right = n - 1, result = 0.
  4. While left <= right: if nums[left] + nums[right] <= target, add pow2[right - left] to result and move left right by one. Otherwise move right left by one, because that value is too large for this min and for every larger min.
  5. Return result modulo 10^9 + 7.

Step-by-step example

nums = [3,5,6,7], target = 9
  1. The array is already sorted. left = 0 (value 3), right = 3 (value 7).
  2. 3 + 7 = 10 > 9, so 7 can never be the max with min 3 or more. right = 2.
  3. 3 + 6 = 9 <= 9. With 3 as the min, the 2 elements 5 and 6 are free: 2^2 = 4 subsequences ([3], [3,5], [3,6], [3,5,6]). result = 4, left = 1.
  4. 5 + 6 = 11 > 9, right = 1. 5 + 5 = 10 > 9, right = 0. Now left > right and the loop ends.
  5. The answer is 4.

Code: Python, Java, C++

1class Solution:
2    def numSubseq(self, nums: List[int], target: int) -> int:
3        MOD = 10**9 + 7
4        nums.sort()
5        n = len(nums)
6        pow2 = [1] * n
7        for k in range(1, n):
8            pow2[k] = pow2[k - 1] * 2 % MOD
9        left, right = 0, n - 1
10        result = 0
11        while left <= right:
12            if nums[left] + nums[right] <= target:
13                result = (result + pow2[right - left]) % MOD
14                left += 1
15            else:
16                right -= 1
17        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. The two pointer pass is O(n) because each iteration moves one pointer one step, and building the powers table is O(n).

Space

O(n)

The table of powers of two holds n values. Computing powers on the fly with fast exponentiation would drop this to O(1) extra space plus the sort.

Other approaches

Sort + binary search per min (time O(n log n), space O(n))

For each left, binary search the last index whose value is at most target - nums[left], and add 2^(that index - left) when it is at least left. Same idea, one log factor more in the counting phase.

Enumerate every subsequence (time O(n * 2^n), space O(n))

Check all 2^n subsequences directly. Only usable for tiny arrays.

Common mistakes

  • Computing 2^(right - left) with floating point pow or plain integer shifts. The exponent reaches 10^5, so use a modular table or modular exponentiation.
  • Using left < right instead of left <= right. The single element subsequence [nums[left]] counts when 2 * nums[left] <= target, which happens when the pointers meet.
  • Overflow in Java or C++ when adding two values just under the modulus. Keep both under 10^9 + 7, so their sum fits in a 32-bit signed int, or use 64-bit.
  • Forgetting to take the modulus after each addition, which lets the running total overflow.

Frequently asked questions

Why is sorting allowed when the problem asks about subsequences?

The condition only looks at the min and the max, which are the same no matter how the chosen elements are ordered. Each subsequence of the original array maps to exactly one set of indices in the sorted array, so the count does not change.

Why is the count 2^(right - left) and not 2^(right - left + 1)?

nums[left] must be in the subsequence because it is the min we fixed. Only the right - left elements after it are free to be in or out.

Why can right move left permanently?

When nums[left] + nums[right] exceeds target, every later min is at least nums[left], so nums[right] is too large for all of them. It never needs to be considered again.