Number of Subsequences That Satisfy the Given Sum Condition (LeetCode 1498): Solution and Explanation
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
- Sort
nums. - Precompute
pow2[k] = 2^k mod 10^9 + 7forkfrom 0 ton - 1. - Set
left = 0,right = n - 1,result = 0. - While
left <= right: ifnums[left] + nums[right] <= target, addpow2[right - left]toresultand moveleftright by one. Otherwise moverightleft by one, because that value is too large for this min and for every larger min. - Return
resultmodulo 10^9 + 7.
Step-by-step example
nums = [3,5,6,7], target = 9
- The array is already sorted. left = 0 (value 3), right = 3 (value 7).
- 3 + 7 = 10 > 9, so 7 can never be the max with min 3 or more. right = 2.
- 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.
- 5 + 6 = 11 > 9, right = 1. 5 + 5 = 10 > 9, right = 0. Now left > right and the loop ends.
- 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 result1class Solution {
2 public int numSubseq(int[] nums, int target) {
3 final int MOD = 1000000007;
4 Arrays.sort(nums);
5 int n = nums.length;
6 int[] pow2 = new int[n];
7 pow2[0] = 1;
8 for (int k = 1; k < n; k++) {
9 pow2[k] = pow2[k - 1] * 2 % MOD;
10 }
11 int left = 0, right = n - 1;
12 int result = 0;
13 while (left <= right) {
14 if (nums[left] + nums[right] <= target) {
15 result = (result + pow2[right - left]) % MOD;
16 left++;
17 } else {
18 right--;
19 }
20 }
21 return result;
22 }
23}1class Solution {
2public:
3 int numSubseq(vector<int>& nums, int target) {
4 const int MOD = 1000000007;
5 sort(nums.begin(), nums.end());
6 int n = nums.size();
7 vector<int> pow2(n, 1);
8 for (int k = 1; k < n; k++) {
9 pow2[k] = pow2[k - 1] * 2 % MOD;
10 }
11 int left = 0, right = n - 1;
12 int result = 0;
13 while (left <= right) {
14 if (nums[left] + nums[right] <= target) {
15 result = (result + pow2[right - left]) % MOD;
16 left++;
17 } else {
18 right--;
19 }
20 }
21 return result;
22 }
23};Time and space complexity
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).
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.