1442. Candy Bounds Ways

Medium3.5 points estimatedCombinatoricsMaths

At a school fair, a teacher hands out exactly candies identical candies to children distinct children, all of whom queue in a fixed order. The fairness rule says each child must receive at least low and at most high candies, and every candy must be given away.

Return the number of different ways to do this, modulo 1000000007. Two ways differ if some child gets a different number of candies. If no valid way exists (for example low > high, or too few candies), return 0. A table of all distributions is far too big; the intended solution uses factorials with inverse factorials and inclusion-exclusion in O(candies + children) time and space.

Example 1

Input:
candies = 4children = 2low = 1high = 3
Output:
3
Explanation:

Each of 2 children gets 1 to 3 candies and the total is 4, so the splits (1,3), (2,2) and (3,1) work, giving 3.

Example 2

Input:
candies = 5children = 3low = 0high = 2
Output:
3
Explanation:

Three children each get 0 to 2 candies and the total is 5, so the only multiset is {1, 2, 2}, which can be arranged in 3 orders.

Example 3

Input:
candies = 3children = 2low = 2high = 5
Output:
0
Explanation:

Two children need at least 2 candies each, which is 4, but only 3 exist, so no split is valid and the answer is 0.

Constraints

0 ≤ candies ≤ 106

1 ≤ children ≤ 105

0 ≤ low, high ≤ 106

Answer modulo 1000000007. Products of residues exceed 253, so use BigInt or a split multiplication in JavaScript; children * low needs 64-bit integers.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(candies + children)
Space
O(candies + children)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…