The Wayback Machine - https://web.archive.org/web/20241004204229/https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
Open In App

Space and time efficient Binomial Coefficient

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Here the function takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). 

Example: 

Input: n = 4 and k = 2
Output: 6
Explanation: 4 C 2 is 4!/(2!*2!) = 6
Input: n = 5 and k = 2
Output: 10
Explanation: 5 C 2 is 5!/(3!*2!) = 10

We have discussed O(n*k) time and O(k) extra space algorithm in this post. The value of C(n, k) can be calculated in O(k) time and O(1) extra space.

Approach:

  1. Change r to n-r if r is greater than n-r. and create a variable to store the answer.
  2. Run a loop from 0 to r-1
  3. In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter.
  4. So the answer will be equal to ((n/1)*((n-1)/2)*…*((n-r+1)/r) which is equal to nCr.
C(n, k) 
= n! / (n-k)! * k!
= [n * (n-1) *....* 1]  / [ ( (n-k) * (n-k-1) * .... * 1) * 
                            ( k * (k-1) * .... * 1 ) ]
After simplifying, we get
C(n, k) 
= [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1]

Also, C(n, k) = C(n, n-k)  
// r can be changed to n-r if r > n-r 

Following implementation uses the above formula to calculate C(n, k). 

C++




// Program to calculate C(n, k)
  
#include <bits/stdc++.h>
using namespace std;
  
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    int res = 1;
  
    // Since C(n, k) = C(n, n-k)
    if (k > n - k)
        k = n - k;
  
    // Calculate value of
    // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
    for (int i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }
  
    return res;
}
  
// Driver Code
int main()
{
    int n = 8, k = 2;
    cout << "Value of C(" << n << ", " << k << ") is "
         << binomialCoeff(n, k);
    return 0;
}
  
// This is code is contributed by rathbhupendra


C




// Program to calculate C(n, k)
#include <stdio.h>
  
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    int res = 1;
  
    // Since C(n, k) = C(n, n-k)
    if (k > n - k)
        k = n - k;
  
    // Calculate value of
    // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
    for (int i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }
  
    return res;
}
  
/* Driver program to test above function*/
int main()
{
    int n = 8, k = 2;
    printf("Value of C(%d, %d) is %d ", n, k,
           binomialCoeff(n, k));
    return 0;
}


Java




// Program to calculate C(n, k) in java
class BinomialCoefficient {
    // Returns value of Binomial Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
        int res = 1;
  
        // Since C(n, k) = C(n, n-k)
        if (k > n - k)
            k = n - k;
  
        // Calculate value of
        // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
        for (int i = 0; i < k; ++i) {
            res *= (n - i);
            res /= (i + 1);
        }
  
        return res;
    }
  
    /* Driver program to test above function*/
    public static void main(String[] args)
    {
        int n = 8;
        int k = 2;
        System.out.println("Value of C(" + n + ", " + k
                           + ") "
                           + "is"
                           + " " + binomialCoeff(n, k));
    }
}
// This Code is Contributed by Saket Kumar


Python3




# Python program to calculate C(n, k)
  
# Returns value of Binomial Coefficient
# C(n, k)
def binomialCoefficient(n, k):
    # since C(n, k) = C(n, n - k)
    if(k > n - k):
        k = n - k
    # initialize result
    res = 1
    # Calculate value of 
    # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]
    for i in range(k):
        res = res * (n - i)
        res = res // (i + 1)
    return res
  
# Driver program to test above function 
n = 8
k = 2
res = binomialCoefficient(n, k)
print("Value of C(% d, % d) is % d" %(n, k, res))
  
# This code is contributed by Aditi Sharma


C#




// C# Program to calculate C(n, k)
using System;
  
class BinomialCoefficient {
  
    // Returns value of Binomial
    // Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
        int res = 1;
  
        // Since C(n, k) = C(n, n-k)
        if (k > n - k)
            k = n - k;
  
        // Calculate value of [n * ( n - 1) *---* (
        // n - k + 1)] / [k * (k - 1) *----* 1]
        for (int i = 0; i < k; ++i) {
            res *= (n - i);
            res /= (i + 1);
        }
  
        return res;
    }
  
    // Driver Code
    public static void Main()
    {
        int n = 8;
        int k = 2;
        Console.Write("Value of C(" + n + ", " + k + ") "
                      + "is"
                      + " " + binomialCoeff(n, k));
    }
}
  
// This Code is Contributed by
// Smitha Dinesh Semwal.


PHP




<?php
// Program to calculate C(n, k)
// Returns value of Binomial 
// Coefficient C(n, k)
  
function binomialCoeff($n, $k)
{
    $res = 1;
  
    // Since C(n, k) = C(n, n-k)
    if ( $k > $n - $k )
        $k = $n - $k;
  
    // Calculate value of 
    // [n * (n-1) *---* (n-k+1)] / 
    // [k * (k-1) *----* 1]
    for ($i = 0; $i < $k; ++$i)
    {
        $res *= ($n - $i);
        $res /= ($i + 1);
    }
  
    return $res;
}
  
    // Driver Code
    $n = 8;
    $k = 2;
    echo " Value of C ($n, $k) is ",
             binomialCoeff($n, $k);
  
// This code is contributed by ajit.
?>


Javascript




<script>
  
// Program to calculate C(n, k)
  
// Returns value of Binomial Coefficient C(n, k)
function binomialCoeff(n, k)
{
    let res = 1;
  
    // Since C(n, k) = C(n, n-k)
    if (k > n - k)
        k = n - k;
  
    // Calculate value of
    // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
    for (let i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }
  
    return res;
}
  
  
// Driver Code
  
    let n = 8;
    let k = 2;
    document.write("Value of C(" + n + ", " + k + ") "
                  + "is"
                  + " " + binomialCoeff(n, k));
  
</script>


Output

Value of C(8, 2) is 28

Complexity Analysis: 

Time Complexity: O(r) A loop has to be run from 0 to r. So, the time complexity is O(r).

Auxiliary Space: O(1) As no extra space is required.

This article is compiled by Aashish Barnwal and reviewed by the GeeksforGeeks team.



Previous Article
Next Article

Similar Reads

Sum of product of r and rth Binomial Coefficient (r * nCr)
Given a positive integer n. The task is to find the sum of the product of r and rth Binomial Coefficient. In other words find: ? (r * nCr), where 0 <= r <= n.Examples: Input : n = 2 Output : 4 0.2C0 + 1.2C1 + 2.2C2 = 0*2 + 1*2 + 2*1 = 4 Input : n = 5 Output : 80 Method 1 (Brute Force) : The idea is to iterate a loop i from 0 to n and evaluate
9 min read
Maximum binomial coefficient term value
Given a positive integer n. The task is to find the maximum coefficient term in all binomial coefficient. The binomial coefficient series is nC0, nC1, nC2, ...., nCr, ...., nCn-2, nCn-1, nCn the task is to find maximum value of nCr. Examples: Input : n = 4 Output : 6 4C0 = 1 4C1 = 4 4C2 = 6 4C3 = 1 4C4 = 1 So, maximum coefficient value is 6. Input
11 min read
Central binomial coefficient
Given an integer N, the task is to find the [Tex]N^{th} [/Tex]Central binomial coefficient. The first few Central binomial coefficients for N = 0, 1, 2, 3... are 1, 2, 6, 20, 70, 252, 924, 3432..... Examples: Input: N = 3 Output: 20 Explanation: [Tex]N^{th} [/Tex]Central Binomial Coefficient = [Tex]\binom{2N}{N} [/Tex]= [Tex]\binom{2*3}{3} [/Tex]=
5 min read
Binomial Coefficient | DP-9
The following are the common definitions of Binomial Coefficients. 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 (
15+ min read
Space efficient iterative method to Fibonacci number
Given a number n, find n-th Fibonacci Number. Note that F0 = 0, F1 = 1, F2 = 2, ..... Examples : Input : n = 5 Output : 5 Input : n = 10 Output : 89 We have discussed below recursive solution in method 4 of Program for Fibonacci numbers. F[2][2] = |1, 1| |1, 0| M[2][2] = |1, 1| |1, 0| F[n][n] = fib(n) | fib(n-1) ------------------ fib(n-1)| fib(n-2
9 min read
Find the closest element in Binary Search Tree | Space Efficient Method
Given a binary search tree and a target node K. The task is to find the node with the minimum absolute difference with given target value K. NOTE: The approach used should have constant extra space consumed O(1). No recursion or stack/queue like containers should be used. Examples: Input: k = 4 Output: 4 Input: k = 18 Output: 17 A simple solution m
10 min read
What is the difference between Auxiliary space and Space Complexity?
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm: Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its workSpace Complexity: Space complexity is the total space taken by the algorithm with respect
4 min read
Various load balancing techniques used in Hash table to ensure efficient access time
Load balancing refers to the process of distributing workloads evenly across multiple servers, nodes, or other resources to ensure optimal resource utilization, maximize output, minimize response time, and avoid overload of any single resource. Load balancing helps to improve the reliability and scalability of applications and systems, as well as r
3 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Time and Space complexity of 1-D and 2-D Array Operations
The time and space complexity of one-dimensional and two-dimensional array operations can vary depending on the specific operation. Here, we'll discuss common array operations and provide insights into their time and space complexities for one-dimensional and two-dimensional arrays. One-Dimensional Array Operations: Accessing an Element by Index:Ti
3 min read
Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
Our task is to design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be performed with time complexity O(1). To implement SpecialStack, you should onl
15+ min read
Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
Given an unsorted array of distinct numbers, write a function that returns true if array consists of consecutive numbers. Examples : Input : arr[] = {5, 4, 2, 1, 3} Output : Yes Input : arr[] = {2, 1, 0, -3, -1, -2} Output : YesRecommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed three different app
6 min read
Time and Space Complexity of DFS and BFS Algorithm
The time complexity of both Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms is O(V + E), where V is the number of vertices and E is the number of edges in the graph. The space complexity of DFS is O(V), where V represents the number of vertices in the graph, and for BFS, it is O(V), where V represents the number of vertices in th
2 min read
Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear at
11 min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
Fibonomial coefficient and Fibonomial triangle
Fibonomial Coefficient: In mathematics, the Fibonomial coefficients or Fibonacci-binomial coefficients are defined as[Tex]\binom{n}{k}_f = \frac{F_n F_{n-1}....F_{n-k+1} }{F_k F_{k-1}....F1} = \frac{n_F!}{k_F!(n-k)_F!} [/Tex]where n and k are non-negative integers, 0 ? k ? n, Fj is the j-th Fibonacci number and n!F is the nth Fibonorial, where 0!F,
11 min read
Range and Coefficient of range of Array
Given an array arr of integer elements, the task is to find the range and coefficient of range of the given array where: Range: Difference between the maximum value and the minimum value in the distribution. Coefficient of Range: (Max – Min) / (Max + Min). Examples: Input: arr[] = {15, 16, 10, 9, 6, 7, 17} Output: Range : 11 Coefficient of Range :
7 min read
Find maximum in a stack in O(1) time and O(1) extra space
Given a stack of integers. The task is to design a special stack such that the maximum element can be found in O(1) time and O(1) extra space. Examples: Given Stack : 2 5 1 64 --> Maximum So Output must be 64 when getMax() is called. Below are the different functions designed to push and pop elements from the stack. Push(x) : Inserts x at the to
11 min read
Case-specific sorting of Strings in O(n) time and O(1) space
Given a string str consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase characters separately such that if the ith place in the original string had an uppercase character then it should not have a lowercase character after being sorted and vice versa.Examples: Input: str = "gEeksfOrgEEkS" Output: eEfggkEkrEO
8 min read
Count Possible Decodings of a given Digit Sequence in O(N) time and Constant Auxiliary space
Given a digit sequence S, the task is to find the number of possible decodings of the given digit sequence where 1 represents 'A', 2 represents 'B' ... and so on up to 26, where 26 represents 'Z'. Examples: Input: S = "121" Output: 3 The possible decodings are "ABA", "AU", "LA" Input: S = "1234" Output: 3 The possible decodings are "ABCD", "LCD", "
6 min read
Time Complexity and Space Complexity
Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on.Shows a direc
14 min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Time and Space Complexity Analysis of Tree Traversal Algorithms
Let us discuss the Time and Space complexity of different Tree Traversal techniques, such as Inorder Traversal, Preorder Traversal, Postorder Traversal, etc. Time Complexity of Tree Traversal AlgorithmsLet us see different corner cases: Complexity function T(n) — for all problems where tree traversal is involved — can be defined as: T(n) = T(k) + T
2 min read
Time and Space Complexity analysis of Stack operations
What is Stack?Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate wh
15+ min read
Find the maximum repeating number in O(n) time and O(1) extra space
Given an array of size n, the array contains numbers in the range from 0 to k-1 where k is a positive integer and k <= n. Find the maximum repeating number in this array. For example, let k be 10 the given array be arr[] = {1, 2, 2, 2, 0, 2, 0, 2, 3, 8, 0, 9, 2, 3}, the maximum repeating number would be 2. The expected time complexity is O(n) an
8 min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1. Examples: Input :
10 min read
Merge Sort with O(1) extra space merge and O(n log n) time [Unsigned Integers Only]
We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 612 856 945 999Recommended PracticeMerge SortTry
10 min read
Count Fibonacci numbers in given range in O(Log n) time and O(1) space
Given a range, count Fibonacci numbers in given range. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Example : Input: low = 10, high = 100 Output: 5 There are five Fibonacci numbers in given range, the numbers are 13, 21, 34, 55 and 89. Input: low = 10, high = 20 Output: 1 There is only one Fibonacci Number, 13. I
5 min read
Design a stack that supports getMin() in O(1) time and O(1) extra space
Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must have a time and space complexity of O(1). Note: To implement SpecialStack, you should only use s
15+ min read