Skip to content
EasyDpAI interview only

Binomial Coefficient nCr Mod

Asked atamazonmicrosoftgoldman-sachsadobe

01 · Problem

Given two non-negative integers n and r, return C(n, r) — the number of ways to choose r items from n distinct items — modulo 10^9 + 7.

Build it with dynamic programming using Pascal's rule C(i, j) = C(i-1, j-1) + C(i-1, j). By definition C(n, 0) = 1 (including C(0, 0) = 1), and when r > n the answer is 0.

02 · Examples

Example 01
Input
n = 5, r = 2
Output
10

There are 10 ways to choose 2 items from 5: (5 * 4) / 2 = 10.

Example 02
Input
n = 3, r = 5
Output
0

You cannot choose 5 items from only 3, so the answer is 0.

Example 03
Input
n = 10, r = 3
Output
120

(10 * 9 * 8) / (3 * 2 * 1) = 120.

03 · Constraints

  • 010 <= n <= 1000
  • 020 <= r <= 1000
  • 03Return the answer modulo 109 + 7

04 · Optimal complexity

Time
O(n * r)
Space
O(r)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.