KatInterview

Valid Subsets Bounded by Their Spread

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssortingcombinatorics

Last 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 lo be the smallest value among those chosen and hi be the largest. A single chosen element counts as both. The selection qualifies when lo + 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 modulo 1_000_000_007.

Constraints

  • 1 <= len(vals) <= 10^5
  • 1 <= vals[i] <= 10^6
  • 1 <= limit <= 10^6
  • The true count can exceed 2^100000, so the answer is always returned modulo 10^9 + 7 and is strictly less than 10^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.