TechBuzzPro

Derive LeetCode 2929 Formula: Distribute Candies

· 5 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

LeetCode 2929 asks for the number of ways to distribute n identical candies among k children so that each child gets between limit and limit candies (inclusive). The direct brute-force triple loop is too slow for large inputs, but a closed-form formula runs in O(1). This guide derives that formula step by step, so you can implement it confidently and understand why it works.

What You'll Need

  • Basic algebra skills (summation, combinations).
  • Familiarity with the stars-and-bars combinatorial method.
  • Pen and paper to follow the derivation.

Step-by-Step

  1. Restate the problem mathematically. We need the number of integer solutions to:

    x₁ + x₂ + x₃ = n, with 0 ≤ xᵢ ≤ limit for each i.

    Here xᵢ is the number of candies given to child i. The limit is the same for all children.

  2. Start with the unrestricted count. Without the upper bound, the number of non-negative solutions is given by stars and bars:

    C(n + 3 - 1, 3 - 1) = C(n + 2, 2).

    This counts all distributions where each child gets at least 0 candies.

  3. Subtract cases where one child exceeds the limit. If child 1 gets more than limit candies, set y₁ = x₁ - (limit + 1). Then y₁ ≥ 0 and the equation becomes:

    y₁ + x₂ + x₃ = n - (limit + 1).

    The number of solutions for this one violation is C(n - (limit + 1) + 2, 2) = C(n - limit + 1, 2), provided n - limit - 1 ≥ 0. If the top argument is negative, the count is 0.

    Since any of the 3 children could be the violator, subtract 3 × C(n - limit + 1, 2).

  4. Add back cases where two children exceed the limit. If both child 1 and child 2 exceed, set y₁ = x₁ - (limit + 1) and y₂ = x₂ - (limit + 1). Then:

    y₁ + y₂ + x₃ = n - 2(limit + 1).

    The number of solutions is C(n - 2(limit + 1) + 2, 2) = C(n - 2·limit - 1, 2).

    There are C(3, 2) = 3 ways to choose which two children violate, so add 3 × C(n - 2·limit - 1, 2).

  5. Subtract cases where all three exceed. If all three exceed, set yᵢ = xᵢ - (limit + 1) for each i. Then:

    y₁ + y₂ + y₃ = n - 3(limit + 1).

    The number of solutions is C(n - 3(limit + 1) + 2, 2) = C(n - 3·limit - 2, 2).

    Subtract this once, because we over-subtracted it in the previous step.

  6. Combine into the final formula. The inclusion-exclusion principle gives:

    Ways = C(n + 2, 2) - 3·C(n - limit + 1, 2) + 3·C(n - 2·limit - 1, 2) - C(n - 3·limit - 2, 2).

    Each binomial coefficient is defined as 0 if its top argument is less than 2 (or negative).

  7. Simplify to the O(1) expression. Expand each combination and combine like terms. After simplification (which you can verify algebraically), the formula reduces to:

    Ways = (n + 2)(n + 1)/2 - 3·(n - limit + 1)(n - limit)/2 + 3·(n - 2·limit - 1)(n - 2·limit - 2)/2 - (n - 3·limit - 2)(n - 3·limit - 3)/2.

    This is the formula you implement.

  8. Handle edge cases. If n > 3·limit, the answer is 0 because even giving every child the maximum leaves candies left over. If n < 0 (not possible in the problem) the answer is 0. Also, if limit is very large, the extra terms vanish because their top arguments become negative, leaving just C(n+2,2).

Common Mistakes

  • Forgetting the inclusion-exclusion signs. The pattern is: subtract one-violation cases, add two-violation cases, subtract three-violation cases. Getting the sign wrong on the last term is a frequent error.
  • Using C(n,2) instead of C(n+2,2). The stars-and-bars formula for 3 variables is C(n+2,2), not C(n,2). Double-check the top argument.
  • Not zeroing negative binomials. In many programming languages, C(a,b) is undefined or returns 0 for negative a. You must explicitly check if the top argument is less than 2 and return 0.
  • Assuming limit is small. The formula works for any limit, but if you try to brute-force with a loop when limit is large, you'll time out.

Tips

  • Test with small examples. For n=3, limit=2, the formula gives C(5,2) - 3·C(2,2) + 0 - 0 = 10 - 3 = 7. Indeed, the valid distributions are (0,1,2) permutations and (1,1,1) — 7 total.
  • Use long long in C++/Java. The intermediate products can exceed 32-bit int. In Python, integers are arbitrary precision, but in other languages use 64-bit.
  • Precompute combinations if you prefer. You could use a DP approach, but the formula is faster and simpler.
  • Derive the formula once, then memorize the pattern. The inclusion-exclusion structure appears in many combinatorics problems.

Troubleshooting

  • My answer is negative. Check the sign of the last term. You should subtract it, not add. Also verify that you are zeroing out negative binomials.
  • My answer is too large. You might be using C(n+3,3) instead of C(n+2,2). Also check that you are using the correct limit in each term: n - limit + 1, n - 2·limit - 1, n - 3·limit - 2.
  • Edge case n > 3·limit gives 0, but my formula gives something else. In that case, the last term should be negative enough to cancel everything. If you are not zeroing negative binomials, you'll get a wrong positive number. Always explicitly return 0 when n > 3·limit.
  • My formula works for small n but fails for large n. Check for integer overflow. Use a 64-bit type or Python's big integers.

Frequently Asked Questions

  1. Why does the formula have four terms? Because there are up to three children who can violate the upper bound. Inclusion-exclusion requires alternating signs for each subset of violators.
  2. Can I use this formula for any number of children? No, this specific formula is for exactly 3 children. For k children, the pattern generalizes to k terms, but the coefficients become binomial coefficients C(k, i).
  3. What if limit is 0? Then each child must get 0 candies, so the answer is 1 if n=0, otherwise 0. The formula handles this: for n=0, C(2,2)=1 and all other terms are 0.
  4. What if n is less than limit? Then the upper bound is not restrictive, and the answer is simply C(n+2,2). The extra terms become 0 because their top arguments are negative.
  5. Is there a dynamic programming solution? Yes, you can use DP with states (index, remaining candies) in O(n·k) time, but the formula is O(1) and is the intended optimal solution.
  6. How do I handle modulo in the formula? If the problem asks for modulo 10⁹+7, compute each combination modulo M using modular inverses or precomputed factorials, then apply the additions/subtractions with modulo.