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
Sub-Multisets With Bounded Sum INPUT nums array: 1 2 2 [0] [1] [2] Target Range [l, r]: [1, 4] Occurrences: occ[1] = 1 occ[2] = 2 occ[0] = 0 ALGORITHM STEPS 1 Count Occurrences Group nums by value 2 Init DP Array dp[0..r] = 0, dp[0] = 1 3 Process Each Value Update dp with sliding window 4 Sum Range [l,r] Return sum(dp[l..r]) DP Table (sum counts): sum: 0 1 2 3 4 5 1 1 1 1 1 1 range [1,4] Valid: {1}, {2}, {1,2}, {2,2} FINAL RESULT Answer: 4 Valid Sub-Multisets: {1} sum = 1 OK {2} sum = 2 OK {1, 2} sum = 3 OK {2, 2} sum = 4 OK 4 valid subsets found Key Insight: Use DP with space optimization: dp[s] = count of ways to form sum s. For each unique value v with count c, update dp using sliding window technique to avoid recomputing. Time: O(r * unique_values), Space: O(r). Final: sum dp[l..r]. TutorialsPoint - Count of Sub-Multisets With Bounded Sum | Optimized DP with Space Reduction
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