Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Math & Number Theory/Combinatorics mod p (nCr, Catalan, stars and bars)

Technique · CP 2400+

Lagrange Interpolation

If the answer f(n) is a polynomial of degree d in n (sum of i^k has degree k+1), compute f(0..d) directly. Then evaluate f at a huge n with Lagrange's formula in O(d), using prefix and suffix products.

Learn firstCombinatorics mod p (nCr, Catalan, stars and bars)Binary Exponentiation (fast power)
0%
mastery
0/2 solved
Practise nextStranger Trees
IdeaPracticePitfalls

Recognise it

The signal

n up to 1e9-1e18, but the answer is a low-degree polynomial in n

  1. 1Brute force

    Sum directly up to n: O(n).

  2. 2The observation

    n is too large to iterate.

  3. 3Why it works

    A degree-d polynomial is determined by any d+1 points.

Reach for it when

  • +sum of i^k with k <= 1e6
  • +a DP whose values are polynomials in a large parameter

Not when

  • ×the answer is not polynomial in n (exponential terms call for matexp)

Practice

Next

Stranger Trees

0/2 solved
  • Stranger TreesCodeforces2600
  • The Sum of the k-th PowersCodeforces2600

Pitfalls

Misconceptions

  • !using d points instead of d+1
  • !O(d2) evaluation when consecutive integer points allow O(d)
Go deeper1 combinations · resources

Combinations

  • Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem+Lagrange Interpolation

    count spanning trees sharing exactly k edges with a given tree, n <= 100

    Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem:
    matrix-tree determinants for spanning trees with weighted edges
    Lagrange Interpolation:
    recover the polynomial in x from n evaluations

    Stranger Trees

Resources

  • Binary exponentiationcp-algorithms · article
  • Sieve of Eratosthenescp-algorithms · article
  • Modular inversecp-algorithms · article
  • DivisibilityUSACO Guide · course
  • CombinatoricsUSACO Guide · course
  • Math cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems