Number of Subsequences That Satisfy the Given Sum Condition

medium

You are given an array of integers nums and an integer target.

Count every non-empty subsequence of nums whose smallest and largest element together satisfy min + max <= target. A subsequence keeps the relative order of nums but may drop any elements — what matters here is only the two extremes of whatever you pick.

Because the count can be astronomically large, return it modulo 10^9 + 7.

Note that a subsequence is chosen by positions, so equal values at different indices count as different subsequences.

Hints

The rule only ever looks at two numbers in a chosen set — the smallest and the largest. Does the order of the other elements matter at all?
If order does not matter, what happens if you sort the array first? Now the min and max of any window are just its two ends.
Sort, then fix the smallest element with a left pointer and find the farthest right pointer that still fits. Everything strictly between them is a free in-or-out choice — that is 2^(right - left) subsequences.

Common doubts

The rule depends only on the min and max of a chosen set, and those are unchanged by reordering. Sorting does not change how many valid sets exist — it only makes the extremes easy to locate.
The left element is always included as the minimum, so it is not a free choice. Only the elements strictly between left and right are optional, and there are right - left of them.
Yes. Subsequences are chosen by index, so two equal values at different positions form different subsequences — that is why repeats increase the count.

Interview follow-ups

Same sort, but a sliding window: expand right while nums[right] - nums[left] <= target, and for each right add 2^(right - left - ... ) style block counts, being careful not to double-count.
Do the sum in a 64-bit type before comparing, or note that the comparison itself never needs the modulus — only the count does.

Fun facts

  • The 'fix one endpoint, count the free middle as 2^k' idea is the same counting trick behind many subset-sum and interval-counting problems.
  • Precomputing powers of two under a modulus is a staple you will reuse in combinatorics-heavy problems like counting paths, Catalan-number variants, and binomial-coefficient tables.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [3,5,6,7], target = 9
Output: 4
The valid subsequences are [3], [3,5], [3,5,6], [3,6] — each has min + max <= 9.
Example 2
Input: nums = [3,3,6,8], target = 10
Output: 6
Repeated values count separately: [3], [3], [3,3], [3,6], [3,6], [3,3,6].
Example 3
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
There are 63 non-empty subsequences; only [6,7] and [7] break the rule, leaving 61.
Constraints

- 1 <= nums.length <= 10^5 - 1 <= nums[i] <= 10^6 - 1 <= target <= 10^6

Solve this problem →