Skip to main content

How to calculate the number of permutations of n elements?

Short answer

The number of permutations of n distinct elements equals n! (n factorial). By definition, n! = 1 · 2 · 3 · … · n, and 0! = 1.

Detailed explanation

What a factorial is

  • Definition: n! = 1 · 2 · 3 · … · n for n ≥ 1; by convention 0! = 1.
  • Recurrent: n! = n · (n − 1)!, where 0! = 1.
  • Example: 5! = 1 · 2 · 3 · 4 · 5 = 120.

Where the formula comes from

A permutation is an ordering of all n distinct elements. Any of the n elements can go in the first position, any of the remaining (n − 1) in the second, (n − 2) in the third, and so on until the elements run out. Multiplying the number of choices at each step gives n · (n − 1) · (n − 2) · … · 2 · 1 = n!.

Permutation examples

  • n = 3: 3! = 6. Permutations of {A, B, C}: ABC, ACB, BAC, BCA, CAB, CBA.
  • n = 5: 5! = 120.
  • n = 0: 0! = 1 (one "empty" permutation).

Common interview variations

  • Permutations without repetition (ordered selections of k out of n): A(n, k) = n! / (n − k)!. Example: A(5, 2) = 5 · 4 = 20.
  • Permutations with repetition: if among n elements there are repeated groups of sizes m1, m2, …, mr (m1 + … + mr = n), the number of distinct permutations equals n! / (m1! · m2! · … · mr!). Example: permutations of the word "ANNA" (letters: A×2, N×2) - 4! / (2! · 2!) = 6.
  • Circular permutations (arrangements in a circle, where rotations count as identical): (n − 1)!.
  • Ordered sequences of length k with replacement (selection with repetition): n^k.

Practical notes

  • Factorial grows extremely fast: already 20! ≈ 2.43e18, so use arbitrary-precision integer types (BigInt, arbitrary precision).
  • Watch out for overflow of standard integer types.
  • In many tasks the factorial is not computed directly - fractions are simplified instead (for example, in A(n, k) the product is reduced).

Code: computing n! in practice

JavaScript (BigInt):

function factorial(n) { if (!Number.isInteger(n)) throw new TypeError('n must be an integer'); if (n < 0) throw new RangeError('n must be >= 0'); let result = 1n; const N = BigInt(n); for (let i = 2n; i <= N; i++) { result *= i; } return result; // BigInt } // Examples console.log(factorial(0).toString()); // "1" console.log(factorial(5).toString()); // "120" console.log(factorial(25).toString()); // "15511210043330985984000000"

Python:

def factorial(n: int) -> int: if not isinstance(n, int): raise TypeError("n must be an integer") if n < 0: raise ValueError("n must be >= 0") result = 1 for i in range(2, n + 1): result *= i return result # Usage examples print(factorial(0)) # 1 print(factorial(5)) # 120 print(factorial(25)) # 15511210043330985984000000 # Note: the standard library already provides math.factorial(n).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.