Tutorialspoint
Problem
Solution
Submissions

Compute the Binomial Coefficient

Certification: Intermediate Level Accuracy: 50% Submissions: 52 Points: 10

Write a Python function to compute the binomial coefficient C(n, k), which is the number of ways to choose k elements from a set of n elements.

Example 1
  • Input: n = 5, k = 2
  • Output: 10
  • Explanation:
    • Step 1: Calculate C(5,2) which gives the number of ways to choose 2 elements from a set of 5.
    • Step 2: Using the formula C(n,k) = n! / (k! * (n-k)!), we have C(5,2) = 5! / (2! * 3!).
    • Step 3: This equals 5! / (2! * 3!) = 120 / (2 * 6) = 120 / 12 = 10.
    • Step 4: So there are 10 ways to choose 2 elements from a set of 5 elements.
Example 2
  • Input: n = 7, k = 3
  • Output: 35
  • Explanation:
    • Step 1: Calculate C(7,3) which gives the number of ways to choose 3 elements from a set of 7.
    • Step 2: Using the formula C(n,k) = n! / (k! * (n-k)!), we have C(7,3) = 7! / (3! * 4!).
    • Step 3: This equals 7! / (3! * 4!) = 5040 / (6 * 24) = 5040 / 144 = 35.
    • Step 4: So there are 35 ways to choose 3 elements from a set of 7 elements.
Constraints
  • 0 <= k <= n <= 50
  • Time Complexity: O(n * k)
  • Space Complexity: O(n * k)
ArraysMicrosoftGoogle
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to compute the binomial coefficient.
  • Initialize a 2D array to store intermediate results.
  • Use the formula C(n, k) = C(n-1, k-1) + C(n-1, k).

Steps to solve by this approach:

 Step 1: Create a 2D array (dp) of size (n+1)×(k+1) to store intermediate results.
 
 Step 2: Initialize the base cases in the dp table: - dp[i][0] = 1 (ways to choose 0 items from i items) - dp[i][i] = 1 (ways to choose i items from i items)  
 Step 3: Fill the dp table using the recurrence relation: dp[i][j] = dp[i-1][j-1] + dp[i-1][j]  
 Step 4: Iterate through values of i from 0 to n  
 Step 5: For each i, iterate through values of j from 0 to min(i,k)  
 Step 6: Apply the base cases or recurrence formula to fill each cell  
 Step 7: Return the final result stored in dp[n][k]

Submitted Code :