Core Concepts
Invariant — a quantity or property that does not change across all operations or steps in a process. If you can identify an invariant, you can determine what states are reachable from the initial state without simulating anything.
Monovariant — a quantity that only ever increases (or only decreases) under each operation. Monvariants prove termination and bound the number of steps; they are weaker than invariants (state is not fixed, just bounded).
Parity argument — reasoning about whether a quantity is odd or even. Many brainteasers reduce to: "this operation changes parity by X; can we ever reach parity Y from parity Z?"
Symmetry argument — if a problem is symmetric, an optimal or forced strategy can be derived by reflecting the opponent's moves or by observing that only one class of positions is distinguishable.
Coloring argument — assign labels (often two colors) to positions or elements; an operation that changes the label in a predictable way constrains reachability. Generalises parity.
Extremal principle — consider the element with the maximum (or minimum) value; argue that it cannot be affected by any operation, or must be affected first. Reduces the problem to a simpler sub-problem.
Counting / bijection — show a one-to-one correspondence between the set of solutions and a set that is easy to count. Turns a hard combinatorial question into a direct formula.
Strategy stealing — in two-player games, if position A is a guaranteed win for whoever moves first, and position B can move to A, then B is also a win. Piggybacks on the first player's advantage.
Types / Variants
| Variant | What it is | Characteristic signal |
|---|---|---|
| Parity-based | Answer depends only on odd/even of a parameter | "Can you reach state X?", counts of moves |
| Pigeonhole | Existence proof that two elements share a property | "Must there exist…", range smaller than count |
| Invariant / Monovariant | Identify a quantity preserved or monotone under operations | Sequences of operations, reachability |
| Symmetry / Strategy stealing | First/second player wins by mirroring | Two-player games with symmetric boards |
| Coloring argument | Assign labels to show reachability is blocked | Grid movement, tiling, alternating positions |
| Modular cycle | Answer repeats with small period k | "After n steps", large n with small pattern |
| Extremal | Focus on max or min element to derive the result | Sorting-like reasoning, "optimal arrangement" |
| Counting / Bijection | Map the solution set to something countable | "How many ways", closed-form expected |
Key Algorithms
Parity Check
Determine the answer by computing the parity of one or more parameters. O(1) time, O(1) space.
Key insight: if every valid operation changes a quantity by an even amount, then parity is preserved. If the target has different parity from the start, it is unreachable.
# Nim Game: first player wins iff n is not a multiple of 4
return n % 4 != 0
Symmetry-Based Game Strategy
For two-player games on a symmetric board, the first player wins by: (1) making any move that creates a symmetric position, then (2) mirroring every subsequent opponent move.
Key insight: after the first player creates symmetry, every move the second player makes has a mirror that the first player can always make. The second player runs out of moves first.
Problem Taxonomy
By Problem Category
| Category | What it asks | Key technique |
|---|---|---|
| Reachability | Can state X be reached from start? | Invariant / parity argument |
| Game theory | Who wins with optimal play? | Parity, Nim theory, symmetry |
| Existence proof | Must a value / pair / overlap exist? | Pigeonhole principle |
| Counting after n steps | State after n operations | Modular cycle reduction |
| Minimum operations | Fewest moves to reach a target | Invariant; monovariant bound |
| Arrangement / placement | Is a valid placement possible? | Coloring argument |
Problem Signal → Technique
| Signal in problem | Likely technique |
|---|---|
| "Can you always win?" / "optimal play" | Parity check or Nim-value |
| "Must there exist two elements such that…" | Pigeonhole principle |
| "After n operations, what is the state?" | Modular cycle — simulate small n |
| "Can you reach configuration Y from X?" | Invariant: find what is preserved |
| Two-player game on a symmetric board | Symmetry / strategy stealing |
| Answer for n = 1,2,3,4 shows obvious cycle | Modular arithmetic |
| Counts of something must be even/odd | Parity argument |
| Tiling / grid coloring with constraints | Coloring / checkerboard argument |
Common Patterns
| Pattern | When it applies | Mechanism |
|---|---|---|
| Simulate small cases, spot the cycle | n is large, answer appears periodic | Try n = 1..8, find the period k, return f(n % k) |
| Count divisors parity | Problems involving factors or divisors | Divisor count is odd iff n is a perfect square |
| XOR accumulation | Find unique or missing element in paired data | Accumulate XOR; pairs cancel |
| Mirror strategy proof | Show first/second player always wins | Construct the mirroring move explicitly |
| Invariant contradiction | Prove a state is unreachable | Show invariant differs between start and target |
| Greedy + parity | Minimum flips / swaps to balance | Count imbalance mod 2; each operation changes balance by fixed amount |
Edge Cases & Pitfalls
-
Jumping to simulation. The most common mistake: implementing a loop for n up to 10^9. If the answer only depends on
n % kor on a closed-form property (perfect square, divisibility), simulation is unnecessary and will TLE. Always check for a cycle or closed form before coding a loop. -
Parity argument applied to the wrong quantity. Not every quantity in the problem has a useful parity. Identify specifically which quantity is preserved, not just "something is even/odd." Verify with 2-3 examples.
-
Pigeonhole mis-application. Pigeonhole guarantees existence of a collision; it does not tell you which pigeons collide or how many. Do not use it to construct a specific answer — only to prove one exists.
-
Off-by-one in cycle detection. When the cycle includes the starting state (0-indexed vs. 1-indexed period), returning
n % kvs.(n - 1) % k + 1can differ. Validate with n = k and n = k + 1. -
Symmetry argument failing on asymmetric boards. The mirror strategy only works when the board or state space is perfectly symmetric. If the first player's move breaks symmetry in a way that disadvantages them, the argument inverts.
-
Assuming the problem is harder than it is. Brainteasers are intentionally disguised. If you have a clean O(1) idea that passes small cases, verify it rather than dismissing it as too simple.
-
Integer overflow in modular arithmetic. For large n with cycle reasoning, compute
n % kbefore any multiplication. In Python, overflow is not an issue, but in a conceptual solution it must be noted.
Implementation Notes
- Python's
math.isqrt(n)gives the integer square root without floating-point error; prefer it overint(math.sqrt(n))which can return n-1 for perfect squares near floating-point boundaries. - When returning a boolean game result (first player wins / loses), verify both the base case and the recurrence before collapsing to
n % k != 0. - Python's arbitrary-precision integers make XOR accumulation safe for any bit-width; no overflow concern.
- For cycle-based problems, always hard-code the first few values rather than deriving them from a formula, then verify the formula matches.
Cross-Topic Relations
| Related topic | Connection |
|---|---|
| Math (number theory) | Divisibility, perfect squares, modular arithmetic underpin many brainteasers |
| Game Theory | Nim, Sprague-Grundy; brainteaser game problems are simplified game-theory instances |
| Bit Manipulation | XOR-based missing/duplicate problems share the same invariant reasoning |
| Dynamic Programming | When a brainteaser's pattern is non-obvious, DP on small n is used to discover it |
| Combinatorics | Counting / bijection problems intersect; pigeonhole is a combinatorial tool |
Interview Reference
Must-Know Problems
Parity / Modular
- Nim Game (LeetCode 292) —
n % 4 != 0 - Bulb Switcher (LeetCode 319) —
isqrt(n) - Stone Game (LeetCode 877) — first player always wins (invariant proof)
Invariant / Reachability
- Reaching Points (LeetCode 780) — work backwards; invariant on
(tx - ty) % sy - Minimum Moves to Equal Array Elements (LeetCode 453) — incrementing n-1 elements equals decrementing one; answer is
sum - n * min
Pigeonhole / Existence
- Find the Duplicate Number (LeetCode 287) — pigeonhole guarantees duplicate; Floyd's cycle (or binary search) finds it
- Couples Holding Hands (LeetCode 765) — greedy + parity on swap count
Symmetry / Game
- Stone Game II / III — verify brute-force DP matches the parity pattern, then collapse
- Flip Game II (LeetCode 294) — memoised game; illustrates when parity alone is insufficient
Clarification Questions to Ask
- "Is n guaranteed to be positive, or can it be zero?" — changes base case for parity arguments.
- "Are values guaranteed distinct?" — affects whether pigeonhole applies directly.
- "Is optimal play defined as maximising score or just winning/losing?" — changes the game-theory model needed.
- "Can I modify the input array?" — relevant for in-place XOR solutions.
Common Interview Mistakes
- Implementing O(n) or O(n log n) simulation when an O(1) formula exists; the interviewer expects the insight, not the brute-force.
- Proving correctness for the pattern by example only ("it works for n = 1,2,3") without arguing why it holds in general.
- Conflating "the first player can always win" (strategy exists) with "the first player wins regardless of opponent moves" (the strategy is deterministic).
- Not checking the edge case n = 0 or n = 1 before applying the general formula.
- Stating the invariant vaguely ("something is always even") without naming the exact quantity.
Typical Follow-Up Escalations
- "Now solve it if there are 3 players instead of 2." — Nim theory generalises; Sprague-Grundy applies. Expected: re-derive the losing positions.
- "Can you prove the formula rather than just pattern-match?" — Expected: state the invariant explicitly and show it is preserved by every valid move.
- "What if the range of values is not 1..n?" — Pigeonhole still applies if the range size is smaller than the count; reformulate.
- "What is the minimum number of operations to reach the target?" — Shifts from reachability to monovariant bounding; expected: show the monovariant decreases by exactly 1 per step.
Read Next
Start reading to get personalized recommendations
Explore Unread
Great job! You've read all available articles