Given an integer values n and k, the task is to find the value of Binomial Coefficient C(n, k).
- A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.
- A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects more formally, the number of k-element subsets (or k-combinations) of a n-element set.
Examples
Input: n = 4, k = 2
Output: 6
Explanation: The value of 4C2 is (4 × 3) / (2 × 1) = 6.
Input: n = 5, k = 2
Output: 10
Explanation: The value of 5C2 is (5 × 4) / (2 × 1) = 10.
Input: n = 6, k = 3
Output: 20
Explanation: The value of 6C3 is (6 × 5 × 4) / (3 × 2 × 1) = 20.
Using recursion - O(2 ^ n) Time and O(n) Space
The idea is to use recursion to find C(n, k).The value of C(n, k) can be recursively calculated using the following standard formula for Binomial Coefficients. C(n, k) = C(n-1, k-1) + C(n-1, k). C(n, 0) = C(n, n) = 1. So we just need to make recursive calls of C(n-1, k-1) and C(n - 1, k). The base conditions will be when k = 0 or value of k and n be equal.
C++
// C++ implementation to find
// Binomial Coefficient using recursion
#include <bits/stdc++.h>
using namespace std;
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k) {
// k can not be grater then k so we return 0 here
if (k > n)
return 0;
// base condition when k and n are equal or k = 0
if (k == 0 || k == n)
return 1;
// Recurvie add the value
return binomialCoeff(n - 1, k - 1)
+ binomialCoeff(n - 1, k);
}
int main() {
int n = 5, k = 2;
cout << binomialCoeff(n, k);
return 0;
}
C
// C implementation to find
// Binomial Coefficient using recursion
#include <stdio.h>
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k) {
// k can not be grater then k so we return 0 here
if (k > n)
return 0;
// base condition when k and n are equal or k = 0
if (k == 0 || k == n)
return 1;
// Recursive add the value
return binomialCoeff(n - 1, k - 1)
+ binomialCoeff(n - 1, k);
}
int main() {
int n = 5, k = 2;
printf("%d", binomialCoeff(n, k));
return 0;
}
Java
// Java implementation to find
// Binomial Coefficient using recursion
class GfG {
// Returns value of Binomial Coefficient C(n, k)
static int binomialCoeff(int n, int k) {
// k can not be grater then k so we
// return 0 here
if (k > n)
return 0;
// base condition when k and n are
// equal or k = 0
if (k == 0 || k == n)
return 1;
// Recursive add the value
return binomialCoeff(n - 1, k - 1)
+ binomialCoeff(n - 1, k);
}
public static void main(String[] args) {
int n = 5, k = 2;
System.out.println(binomialCoeff(n, k));
}
}
Python
# Python implementation to find
# Binomial Coefficient using recursion
# Returns value of Binomial Coefficient C(n, k)
def binomialCoeff(n, k):
# k can not be grater then k so we
# return 0 here
if k > n:
return 0
# base condition when k and n are equal
# or k = 0
if k == 0 or k == n:
return 1
# Recursive add the value
return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k)
n = 5
k = 2
print(binomialCoeff(n, k))
C#
// C# implementation to find
// Binomial Coefficient using recursion
using System;
class GfG {
// Returns value of Binomial Coefficient C(n, k)
static int BinomialCoeff(int n, int k) {
// k can not be grater then k so we
// return 0 here
if (k > n)
return 0;
// base condition when k and n are
// equal or k = 0
if (k == 0 || k == n)
return 1;
// Recursive add the value
return BinomialCoeff(n - 1, k - 1)
+ BinomialCoeff(n - 1, k);
}
static void Main(string[] args) {
int n = 5, k = 2;
Console.WriteLine(BinomialCoeff(n, k));
}
}
JavaScript
// Javascript implementation to find
// Binomial Coefficient using recursion
// Returns value of Binomial Coefficient C(n, k)
function binomialCoeff(n, k) {
// k can not be grater then k so we
// return 0 here
if (k > n)
return 0;
// base condition when k and n are equal
// or k = 0
if (k === 0 || k === n)
return 1;
// Recursive add the value
return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
}
let n = 5, k = 2;
console.log(binomialCoeff(n, k));
Top-Down DP (Memoization) - O(n * k) Time and O(n * k) Space
It should be noted that the above function computes the same subproblems again and again. And have two properties of Dynamic Programming:
1. Optimal Substructure:
The value of C(n, k)depends on the optimal solutions of the subproblemsC(n-1, k-1) and C(n-1, k). By adding these optimal substrutures, we can efficiently calculate the total value of C(n, k).
2. Overlapping Subproblems:
While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. Recursion tree for n = 5 and k = 2. The function C(3, 1) is called two times. For large values of n, there will be many common subproblems.
The Binomial Coefficient C(n, k) is computed recursively, but to avoid redundant calculations, dynamic programming with memoization is used. A 2D table stores previously computed values, allowing efficient lookups instead of recalculating. If a value is already computed, it is returned directly; otherwise, it is computed recursively and stored for future use.
C++
// C++ implementation to find
// Binomial Coefficient using memoization
#include <bits/stdc++.h>
using namespace std;
// Returns value of Binomial Coefficient C(n, k)
int getnCk(int n, int k, vector<vector<int>> &memo) {
// k can not be grater then k so we
// return 0 here
if (k > n)
return 0;
// base condition when k and n are
// equal or k = 0
if (k == 0 || k == n)
return 1;
// Check if pair n and k is already
// calculated then return it from here
if(memo[n][k] != -1) return memo[n][k];
// Recurvie add the value and store to memorize table
return memo[n][k] = getnCk(n - 1, k - 1, memo)
+ getnCk(n - 1, k, memo);
}
int binomialCoeff(int n, int k) {
// Create table for memorization
vector<vector<int>> memo(n + 1, vector<int> (k + 1, -1));
return getnCk(n, k, memo);
}
int main() {
int n = 5, k = 2;
cout << binomialCoeff(n, k);
return 0;
}
Java
// Java implementation to find
// Binomial Coefficient using memoization
import java.util.Arrays;
class GfG {
// Returns value of Binomial Coefficient C(n, k)
static int getnCk(int n, int k, int[][] memo) {
// k cannot be greater than n so we return 0 here
if (k > n)
return 0;
// base condition when k and n are equal or k = 0
if (k == 0 || k == n)
return 1;
// Check if pair n and k is already
// calculated then return it from here
if (memo[n][k] != -1) return memo[n][k];
// Recursive add the value and store to memo table
return memo[n][k] = getnCk(n - 1, k - 1, memo)
+ getnCk(n - 1, k, memo);
}
static int binomialCoeff(int n, int k) {
// Create table for memoization
int[][] memo = new int[n + 1][k + 1];
for (int[] row : memo)
Arrays.fill(row, -1);
return getnCk(n, k, memo);
}
public static void main(String[] args) {
int n = 5, k = 2;
System.out.println(binomialCoeff(n, k));
}
}
Python
# Python implementation to find
# Binomial Coefficient using memoization
def getnCk(n, k, memo):
# k cannot be greater than n so we return 0 here
if k > n:
return 0
# base condition when k and n are equal or k = 0
if k == 0 or k == n:
return 1
# Check if pair n and k is already
# calculated then return it from here
if memo[n][k] != -1:
return memo[n][k]
# Recursive add the value and store to memo table
memo[n][k] = getnCk(n - 1, k - 1, memo) + \
getnCk(n - 1, k, memo)
return memo[n][k]
def binomialCoeff(n, k):
# Create table for memoization
memo = [[-1 for _ in range(k + 1)] for _ in range(n + 1)]
return getnCk(n, k, memo)
n, k = 5, 2
print(binomialCoeff(n, k))
C#
// C# implementation to find
// Binomial Coefficient using memoization
using System;
class GfG {
// Returns value of Binomial
// Coefficient C(n, k)
static int GetnCk(int n, int k, int[,] memo) {
// k cannot be greater than n so we
// return 0 here
if (k > n)
return 0;
// base condition when k and n are
// equal or k = 0
if (k == 0 || k == n)
return 1;
// Check if pair n and k is already
// calculated then return it from here
if (memo[n, k] != -1) return memo[n, k];
// Recursive add the value and store to memo table
return memo[n, k] = GetnCk(n - 1, k - 1, memo)
+ GetnCk(n - 1, k, memo);
}
static int BinomialCoeff(int n, int k) {
// Create table for memoization
int[,] memo = new int[n + 1, k + 1];
for (int i = 0; i <= n; i++)
for (int j = 0; j <= k; j++)
memo[i, j] = -1;
return GetnCk(n, k, memo);
}
static void Main() {
int n = 5, k = 2;
Console.WriteLine(BinomialCoeff(n, k));
}
}
JavaScript
// Javascript implementation to find
// Binomial Coefficient using memoization
function getnCk(n, k, memo) {
// k cannot be greater than n so we
// return 0 here
if (k > n)
return 0;
// base condition when k and n are
// equal or k = 0
if (k === 0 || k === n)
return 1;
// Check if pair n and k is already
// calculated then return it from here
if (memo[n][k] !== -1)
return memo[n][k];
// Recursive add the value and store to memo table
return memo[n][k] = getnCk(n - 1, k - 1, memo)
+ getnCk(n - 1, k, memo);
}
function binomialCoeff(n, k) {
// Create table for memoization
const memo = Array.from({length : n + 1},
() => Array(k + 1).fill(-1));
return getnCk(n, k, memo);
}
const n = 5, k = 2;
console.log(binomialCoeff(n, k));
Using Bottom-Up DP (Tabulation) - O(n * k) Time and O(n * k) Space
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner. Maintain a dp[][] table such that dp[i][j] stores the count all unique possible paths to reach the cell (i, j).
Base Case:
- For i = j and 0 <= i <= n , dp[i][j] = 1
- for j = 0 and 0 <= j <= min(i, k) , dp[i][j] = 1
Recursive Case:
- For i > 1 and j > 1 , dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
C++
// C++ implementation to find
// Binomial Coefficient using tabulation
#include <bits/stdc++.h>
using namespace std;
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k) {
vector<vector<int>> dp(n + 1, vector<int> (k + 1));
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= min(i, k); j++) {
// Base Cases
if (j == 0 || j == i)
dp[i][j] = 1;
// Calculate value using previously
// stored values
else
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
}
return dp[n][k];
}
int main() {
int n = 5, k = 2;
cout << binomialCoeff(n, k);
}
C
// C implementation to find
// Binomial Coefficient using tabulation
#include <stdio.h>
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k) {
int dp[n + 1][k + 1];
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= (i < k ? i : k); j++) {
if (j == 0 || j == i)
dp[i][j] = 1;
// Calculate value using previously
// stored values
else
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
}
return dp[n][k];
}
int main() {
int n = 5, k = 2;
printf("%d", binomialCoeff(n, k));
return 0;
}
Java
// Java implementation to find
// Binomial Coefficient using tabulation
class GfG {
// Returns value of Binomial Coefficient C(n, k)
static int binomialCoeff(int n, int k) {
int[][] dp = new int[n + 1][k + 1];
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++) {
if (j == 0 || j == i)
dp[i][j] = 1;
// Calculate value using previously
// stored values
else
dp[i][j]
= dp[i - 1][j - 1] + dp[i - 1][j];
}
}
return dp[n][k];
}
public static void main(String[] args) {
int n = 5, k = 2;
System.out.println(binomialCoeff(n, k));
}
}
Python
# Python implementation to find
# Binomial Coefficient using tabulation
# Returns value of Binomial Coefficient C(n, k)
def binomialCoeff(n, k):
dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]
# Calculate value of Binomial Coefficient
# in bottom up manner
for i in range(n + 1):
for j in range(min(i, k) + 1):
# Base Cases
if j == 0 or j == i:
dp[i][j] = 1
# Calculate value using previously
# stored values
else:
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
return dp[n][k]
n = 5
k = 2
print(binomialCoeff(n, k))
C#
// C3 implementation to find
// Binomial Coefficient using tabulation
using System;
class GfG {
// Returns value of Binomial Coefficient C(n, k)
public static int BinomialCoeff(int n, int k) {
int[, ] dp = new int[n + 1, k + 1];
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.Min(i, k); j++) {
// Base Cases
if (j == 0 || j == i)
dp[i, j] = 1;
// Calculate value using previously
// stored values
else
dp[i, j]
= dp[i - 1, j - 1] + dp[i - 1, j];
}
}
return dp[n, k];
}
static void Main(string[] args) {
int n = 5, k = 2;
Console.WriteLine(BinomialCoeff(n, k));
}
}
JavaScript
// Javascript implementation to find
// Binomial Coefficient using tabulation
// Returns value of Binomial Coefficient C(n, k)
function binomialCoeff(n, k) {
let dp = Array.from({ length: n + 1 }, () => Array(k + 1).fill(0));
// Calculate value of Binomial Coefficient
// in bottom up manner
for (let i = 0; i <= n; i++) {
for (let j = 0; j <= Math.min(i, k); j++) {
// Base Cases
if (j === 0 || j === i) {
dp[i][j] = 1;
}
// Calculate value using previously
// stored values
else {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
}
}
return dp[n][k];
}
let n = 5, k = 2;
console.log(binomialCoeff(n, k));
Using Space Optimized DP - O(n * k) Time and O(k) Space
In the previous approach using dynamic programming, we derived a relation between states as follows:
- dp[i][j] = dp[i-1][j-1]+dp[i-1][j]
We do not need to maitain whole matrix for this. We can just maintain one array of length k and add dp[j-1] every time to dp[j];
- Use a 1D array dp[] of size k+1 to store binomial coefficients, reducing space complexity to O(k).
- Set dp[0] = 1, representing nC0=1.
- Update dp[j] in reverse order, using the previous values from the same array.
- Each entry dp[j] is updated as dp[j] + dp[j-1] for each row.
- The final value of dp(n,k) is stored in dp[k], and returned.
C++
// C++ program for space optimized Dynamic Programming
// Solution of Binomial Coefficient
#include <bits/stdc++.h>
using namespace std;
int binomialCoeff(int n, int k) {
vector<int> dp(k + 1);
// nC0 is 1
dp[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal triangle using
// the previous row
for (int j = min(i, k); j > 0; j--)
dp[j] = dp[j] + dp[j - 1];
}
return dp[k];
}
int main() {
int n = 5, k = 2;
cout << binomialCoeff(n, k);
return 0;
}
Java
// Java program for space optimized Dynamic Programming
// Solution of Binomial Coefficient
class GfG {
// Returns value of Binomial Coefficient C(n, k)
static int binomialCoeff(int n, int k) {
int[] dp = new int[k + 1];
// nC0 is 1
dp[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal triangle using
// the previous row
for (int j = Math.min(i, k); j > 0; j--)
dp[j] = dp[j] + dp[j - 1];
}
return dp[k];
}
public static void main(String[] args) {
int n = 5, k = 2;
System.out.println(binomialCoeff(n, k));
}
}
Python
# Python program for space optimized Dynamic Programming
# Solution of Binomial Coefficient
def binomialCoeff(n, k):
dp = [0] * (k + 1)
# nC0 is 1
dp[0] = 1
for i in range(1, n + 1):
# Compute next row of pascal triangle using
# the previous row
for j in range(min(i, k), 0, -1):
dp[j] = dp[j] + dp[j - 1]
return dp[k]
n = 5
k = 2
print(binomialCoeff(n, k))
C#
// C# program for space optimized Dynamic Programming
// Solution of Binomial Coefficient
using System;
class GfG {
// Returns value of Binomial Coefficient C(n, k)
static int BinomialCoeff(int n, int k) {
int[] dp = new int[k + 1];
// nC0 is 1
dp[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal triangle using
// the previous row
for (int j = Math.Min(i, k); j > 0; j--)
dp[j] = dp[j] + dp[j - 1];
}
return dp[k];
}
static void Main(string[] args) {
int n = 5, k = 2;
Console.WriteLine(BinomialCoeff(n, k));
}
}
JavaScript
// JavaScript program for space optimized Dynamic
// Programming Solution of Binomial Coefficient
function binomialCoeff(n, k) {
let dp = Array(k + 1).fill(0);
// nC0 is 1
dp[0] = 1;
for (let i = 1; i <= n; i++) {
// Compute next row of pascal triangle using
// the previous row
for (let j = Math.min(i, k); j > 0; j--) {
dp[j] = dp[j] + dp[j - 1];
}
}
return dp[k];
}
let n = 5, k = 2;
console.log(binomialCoeff(n, k));
Related articles:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem