Valid Subsets Bounded by Their Spread
Arrays & HashingAuto-graded · 25 test casesLast updated
Count non-empty index-distinct subsets where the smallest plus largest value stays within a limit, using sorting, two pointers, and modular arithmetic.
Given an integer array vals and an integer limit, find the number of non-empty subsets of vals such that the subset's minimum value plus its maximum value does not exceed limit. Return this count modulo 10^9 + 7.
Subsets are defined by which indices you pick. Two selections that use different index positions are treated as distinct even if the chosen values happen to be identical. Only the set of chosen values determines whether the condition holds — the order you list them does not matter.
Rules
- For any non-empty selection of indices, let
lobe the smallest value among those chosen andhibe the largest. A single chosen element counts as both. The selection qualifies whenlo + hi <= limit. - Every qualifying selection of indices counts as one toward the total, regardless of whether another selection holds the same multiset of values.
- If no selection qualifies, return
0. Otherwise return the total count modulo1_000_000_007.
Constraints
1 <= len(vals) <= 10^51 <= vals[i] <= 10^61 <= limit <= 10^6- The true count can exceed
2^100000, so the answer is always returned modulo10^9 + 7and is strictly less than10^9 + 7.
Examples
Example 1
Input: count_valid_subsets([2, 3, 5, 8], 8)
Output: 6
Example 2
Input: count_valid_subsets([4, 1, 4], 5)
Output: 4
Example 3
Input: count_valid_subsets([7, 9], 10)
Output: 0
Hints
Hint 1
Sorting the array doesn't change the answer — the minimum and maximum of any chosen set are unaffected by reordering. What does sorting let you do with two pointers?
Hint 2
After sorting, fix the leftmost chosen position i as the minimum. The rightmost position j is the maximum. Find the furthest j where a[i] + a[j] <= limit; every position strictly between i and j is a free choice — include it or not.
Hint 3
You need 2^(j−i) quickly for many values of j−i. Precompute a table of powers of two modulo 10^9+7 so each lookup is O(1). Watch the exponent: position i is required, so only the (j−i) positions between i and j are free.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why sorting is safe
The qualifying condition depends only on which values are chosen, not on their positions in the original array. Specifically, only the minimum and maximum of the chosen values matter. Sorting produces a rearrangement of the same elements, and every original index-set maps to exactly one set of positions in the sorted array with the same multiset of values. So counting qualifying sets in the sorted array gives the same total as counting them in the original — including duplicates, which land at distinct positions and are therefore counted as separate sets.
Fixing the minimum position
After sorting into array a, classify every qualifying set by its leftmost (smallest-indexed) chosen position i. That position holds the minimum value a[i]. The rightmost chosen position j holds the maximum a[j]. The set qualifies when a[i] + a[j] <= limit.
For a fixed i, the largest valid j is the rightmost position where this inequality holds. Call it j*. Every position strictly between i and j* is a free choice — include it or exclude it without affecting which element is the minimum or maximum. That gives exactly 2^(j* - i) qualifying sets whose leftmost position is i. Every set is counted exactly once because every non-empty set has a unique leftmost position.
Two-pointer scan
Start with i = 0 and j = n - 1.
- If
a[i] + a[j] <= limit:jis the best right boundary fori. Add2^(j - i)and advanceirightward. - If
a[i] + a[j] > limit:jis too large for thisiand for every futurei(which will only be larger), so shrinkjpermanently.
Each step moves exactly one pointer, so the scan runs in O(n) total iterations. The loop ends when i > j, at which point either all remaining elements fail even as singletons (since a[i] + a[i] > limit when j < i), or nothing is left to examine.
Precomputed power table
Rather than recomputing 2^(j - i) from scratch each iteration, build pw[k] = 2^k mod (10^9 + 7) up front in O(n) time. Each lookup is then O(1).
Edge cases
- Nothing qualifies: The pointers cross before any addition occurs; the function returns
0. - Duplicate values: Equal values sit at distinct positions in the sorted array, so subsets containing different index combinations of the same value are counted separately — exactly what the problem requires.
- Single element: When
i == j, the contribution is2^0 = 1, counting just that lone element, which qualifies only when2 * a[i] <= limit. - Everything qualifies: If
2 * a[n-1] <= limit,jnever moves and the total is2^(n-1) + 2^(n-2) + ... + 1 = 2^n - 1, the count of all non-empty subsets.
Complexity
- Time:
O(n log n)for sorting;O(n)for the power table and the two-pointer scan. - Space:
O(n)for the sorted copy and the power table.
from typing import List
def count_valid_subsets(vals: List[int], limit: int) -> int:
MOD = 1_000_000_007
a = sorted(vals)
n = len(a)
# Precompute powers of two: pw[k] = 2^k mod MOD
pw = [1] * (n + 1)
for k in range(1, n + 1):
pw[k] = pw[k - 1] * 2 % MOD
i, j = 0, n - 1
total = 0
while i <= j:
if a[i] + a[j] <= limit:
# a[i] is the minimum; the (j - i) positions between i and j
# can each be freely included or excluded: 2^(j - i) subsets.
total += pw[j - i]
i += 1
else:
# a[j] is too large to pair with a[i] or any later (larger) element.
j -= 1
return total % MOD