13. nCr
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
Given two integers n and r, return the value of the binomial coefficient C(n, r), defined as the number of ways to choose r objects from a set of n without regard to order. It is given by:
If $r > n$, return 0. It is guaranteed that the result will fit within a 32-bit integer.
📘 Examples
Example 1:
Input:
n = 5, r = 2Output:
10Explanation:
Example 2:
Input:
Output:
Explanation:
Since $r > n$, $C(2,4)=0$.
Example 3:
Input:
Output:
Explanation:
🔒 Constraints
$1 \leq n \leq 100$
$0 \leq r \leq 100$
✅ My Approach
Modular Inverse + Factorials
We compute factorials up to n modulo $10^9+7$, then use Fermat’s little theorem to find modular inverses in $O(n + \log(\text{MOD}))$:
Precompute
fact[i] = i! mod MODfor $0 \le i \le n$.Compute
inv[n] = fact[n]^(MOD-2) mod MODvia fast exponentiation.Build
inv[i-1] = inv[i] * i mod MODfor $i = n$ down to 1 (inverse factorials).Return
Algorithm Steps:
Handle if $r > n$: return 0.
Initialize constants:
MOD = 10^9+7.Allocate two arrays of size
n+1:fact[],inv[].Compute factorials:
Compute inverse factorial of n:
using binary exponentiation in $O(\log,\text{MOD})$.
Compute remaining inverses:
Combine:
🧮 Time and Auxiliary Space Complexity
Expected Time Complexity: $O(n + \log(\text{MOD}))$, since we build factorials in $O(n)$, compute one modular exponentiation in $O(\log,\text{MOD})$, and build inverse factorials in $O(n)$.
Expected Auxiliary Space Complexity: $O(n)$, for storing
fact[]andinv[]arrays of size $n+1$.
🧠 Code (C++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated