Number of Subsequences That Satisfy the Given Sum Condition - Problem

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

Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element in the subsequence is less than or equal to target.

Since the answer may be too large, return it modulo 109 + 7.

Note: A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,5,6,7], target = 9
Output: 4
💡 Note: Valid subsequences: [3], [3,5], [3,6], [3,5,6]. Each has min + max ≤ 9. For [3]: 3+3=6≤9, [5]: 5+5=10>9 (invalid), [6]: 6+6=12>9 (invalid), [7]: 7+7=14>9 (invalid), [3,5]: 3+5=8≤9, [3,6]: 3+6=9≤9, [3,5,6]: 3+6=9≤9.
Example 2 — Smaller Target
$ Input: nums = [3,3,6,8], target = 10
Output: 6
💡 Note: After sorting [3,3,6,8]: valid subsequences include [3], [3], [3,3], [3,6], [3,6] (different 3's), [3,3,6]. Min + max ≤ 10 for each.
Example 3 — All Valid
$ Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
💡 Note: Most subsequences are valid since target is large. Even [6,7] has 6+7=13>12, but many smaller combinations work.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ target ≤ 106

Visualization

Tap to expand
Number of Subsequences - Sum Condition INPUT nums array: 3 5 6 7 0 1 2 3 target = 9 After sorting: 3 5 6 7 left right min + max <= target nums = [3,5,6,7] target = 9 ALGORITHM STEPS 1 Sort Array Sort to use two pointers 2 Two Pointers left=0, right=n-1 3 Check Sum nums[l]+nums[r] <= target 4 Count Subseq Add 2^(r-l) if valid Iterations: l=0,r=3: 3+7=10 > 9 --> r-- l=0,r=2: 3+6=9 <= 9 --> +4 l=1,r=2: 5+6=11 > 9 --> r-- l=1,r=1: done, total = 4 Valid Subsequences: [3], [3,5], [3,6], [3,5,6] FINAL RESULT Valid subsequences found: [3] [3,5] [3,6] [3,5,6] Verification (min+max): [3]: 3+3=6 <= 9 OK [3,5]: 3+5=8 <= 9 OK [3,6]: 3+6=9 <= 9 OK [3,5,6]: 3+6=9 <= 9 OK Output: 4 4 valid subsequences Key Insight: After sorting, if nums[left] + nums[right] <= target, then all 2^(right-left) subsequences with nums[left] as minimum are valid. Two pointers efficiently count without enumeration. TutorialsPoint - Number of Subsequences That Satisfy the Given Sum Condition | Optimal Solution Time: O(n log n) | Space: O(n) for precomputing powers
Asked in
Google 15 Facebook 12 Amazon 8
58.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen