← all cheatsheets

cheatsheet · before you code

Which pattern is this?

Use it when: You've read the problem and don't know where to start.

Pick the family that sounds closest. Each card: the signals you'll see in the statement, then the idea to try.

  • Simulation
    • The statement spells out a process: rounds, turns, a line of people
    • Small limits and no obvious shortcut
    • Digit-by-digit arithmetic with a carry

    Do exactly what the statement describes, step by step (often with a queue or a few counters), and keep the bookkeeping clean.

  • Math shortcut (closed form)
    • The numbers form a known range like 0…n
    • "How many paths/ways" on a plain grid
    • The answer depends only on counts, not on the order of events

    Replace a loop or a search with a formula: Gauss's sum, a combination count, or a counting argument.

  • Recursion on a smaller input
    • The definition is self-similar (row n is built from row n − 1)
    • A list or string that shrinks by one element or pair
    • "This piece + the answer for the rest"

    Trust the call: solve the same problem for a smaller input, then do one step of work to finish yours.

  • Divide and conquer
    • Halving the input halves the work (xⁿ, sorted ranges)
    • The answer combines a left part and a right part
    • Build a balanced structure from a sorted array

    Split the input into halves, solve each half recursively, then combine — about log n levels of work.

  • GCD & prime sieve
    • "Greatest common divisor", or fractions and ratios to simplify
    • Count or list the primes up to n
    • Two cycles must line up again (lcm)

    Euclid's algorithm finds gcd(a, b) in O(log min(a, b)); the sieve of Eratosthenes lists every prime up to n in O(n log log n).

  • Digit peeling (% 10 and / 10)
    • "Reverse the digits" or "is the number a palindrome" without a String
    • Sum, square or count the digits of a number
    • The result must fit in a 32-bit int, or else return 0

    x % 10 reads the last digit and x / 10 drops it; rebuild with rev * 10 + d, and check for overflow before the multiply, not after.