Skip to main content

Mathematics for DSA

Mathematical foundations that frequently appear in coding interviews and competitive programming.

GCD & LCM

Greatest Common Divisor (Euclidean Algorithm)

  • Time: O(log(min(a, b)))
  • Extended Euclidean: finds x, y such that ax + by = gcd(a, b)

Key Properties

  • gcd(a, 0) = a
  • gcd(a, b) = gcd(b, a % b)
  • lcm(a, b) = a * b / gcd(a, b)

Prime Numbers & Sieve of Eratosthenes

Primality Check

Time: O(√n)

Sieve of Eratosthenes

Find all primes up to n:
Time: O(n log log n), Space: O(n)

Prime Factorization

Modular Arithmetic

Essential for problems with “answer mod 10⁹+7”.

Key Rules

  • (a + b) % m = ((a % m) + (b % m)) % m
  • (a * b) % m = ((a % m) * (b % m)) % m
  • (a - b) % m = ((a % m) - (b % m) + m) % m
  • Division requires modular inverse

Modular Exponentiation (Fast Power)

Time: O(log exp)

Modular Inverse

  • a⁻¹ mod m = mod_pow(a, m - 2, m) (when m is prime, by Fermat’s little theorem)

Combinatorics

Basics

  • Permutations: P(n, r) = n! / (n-r)!
  • Combinations: C(n, r) = n! / (r! * (n-r)!)
  • Pascal’s Triangle: C(n, r) = C(n-1, r-1) + C(n-1, r)

Computing nCr mod p

Precompute factorials and inverse factorials:

Probability Basics

  • Useful for randomized algorithms (e.g., reservoir sampling, random pivots)
  • Expected value: linearity of expectation
  • Monte Carlo vs Las Vegas algorithms

Classic Problems

  • Count Primes
  • Pow(x, n)
  • Happy Number
  • GCD of Strings
  • Unique Paths (combinatorics solution)
  • Catalan Numbers
  • Pascal’s Triangle
  • Josephus Problem