Count of Sub-Multisets With Bounded Sum - Problem

You are given a 0-indexed array nums of non-negative integers, and two integers l and r.

Return the count of sub-multisets within nums where the sum of elements in each subset falls within the inclusive range of [l, r].

Since the answer may be large, return it modulo 10^9 + 7.

A sub-multiset is an unordered collection of elements of the array in which a given value x can occur 0, 1, ..., occ[x] times, where occ[x] is the number of occurrences of x in the array.

Note that:

  • Two sub-multisets are the same if sorting both sub-multisets results in identical multisets.
  • The sum of an empty multiset is 0.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,2], l = 1, r = 4
Output: 4
💡 Note: Valid sub-multisets: [1] (sum=1), [2] (sum=2), [1,2] (sum=3), [2,2] (sum=4). All sums are in range [1,4].
Example 2 — With Zeros
$ Input: nums = [0,1,2], l = 1, r = 3
Output: 4
💡 Note: Valid sub-multisets: [1] (sum=1), [2] (sum=2), [1,2] (sum=3), [0,1,2] (sum=3). The zero can be included or excluded.
Example 3 — No Valid Sums
$ Input: nums = [1,2,3], l = 10, r = 15
Output: 0
💡 Note: Maximum possible sum is 1+2+3=6, which is less than l=10. No valid sub-multisets exist.

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • 0 ≤ nums[i] ≤ 2 × 104
  • 1 ≤ l ≤ r ≤ 2.5 × 104

Visualization

Tap to expand
Count Sub-Multisets With Bounded Sumnums = [1,2,2]Input ArrayRange [1, 4]Valid Sum RangeCount = 4Valid Sub-MultisetsValid Sub-Multisets:[1] → sum=1 ✓[2] → sum=2 ✓[1,2] → sum=3 ✓[2,2] → sum=4 ✓All sums are in range [1,4]Output: 4
Understanding the Visualization
1
Input
Array nums and range [l, r]
2
Process
Generate all possible sub-multisets and check sum ranges
3
Output
Count of valid sub-multisets
Key Takeaway
🎯 Key Insight: Use frequency counting + dynamic programming to efficiently count sub-multisets without generating duplicates
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
245 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