VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-ways-choosing-k-balls-from-any-given-a-boxes/

⇱ Count ways choosing K balls from any given A boxes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count ways choosing K balls from any given A boxes

Last Updated : 23 Jul, 2025

Given integers A and K, there are A boxes the first box contains K balls, the Second box contains K + 1 balls, the Third Box contains K + 3 balls so on till the A'th box contains K + A balls, the task for this problem is to count the number of ways of picking K balls from any of the boxes. (Print answer modulo 109 + 7).

Examples:

Input: A = 2, K = 2
Output: 4
Explanation: We have two boxes one with 2 balls let's say Box 1 with Balls {A1, A2} and one with 3 balls let's say Box 2 with balls {B1, B2, B3}

  • First way: we can remove balls A1 and A2 from Box 1.
  • Second way: we can remove balls B1 and B2 from Box 2.
  • Third way: we can remove balls B2 and B3 from Box 2.
  • Forth way : we can remove balls B1 and B3 from Box 2.

Input: A = 3, K = 3
Output: 15

Naive approach: The basic way to solve the problem is as follows:

The basic way to solve this problem is to generate all possible combinations by using a recursive approach.

Time Complexity: O(N!)
Auxiliary Space: O(1)

Efficient Approach:  The above approach can be optimized based on the following idea:

The problem can be solved with combinatorics:

  • Total ways = KCK + K+1CK + K+2CK + ....... +  K+A-1CK
  • we know N+1CM+1 = NCM + NCM+1 that is NCM = N+1CM+1 - NCM+1
  • Total ways = K+1CK+1 + (K+2CK+1 - K+1CK+1) + (K+3CK+1 - K+2CK+1) + ................ + (K+ACK+1 - K+A-1CK-1)
  • Total ways = K+ACK+1
  • Total ways = (K + A)! / ((K + 1)! * (A - 1)!)

Instead of dividing factorials of K + 1 and A - 1, we multiply their modular multiplicative inverses

Follow the steps below to solve the problem:

  • Initializing fact[] array and Precomputing all factorials from 1 to 100000.
  • initializing ANS variable.
  • Calculating the answer by using the above formula.
  • Print the answer.

Below is the implementation of the above approach:


Output
4
15

Time Complexity: O(N)
Auxiliary Space: O(N)

Related Articles:

Comment