Technique · Interview · medium
Invariants & Parity Arguments
Find a quantity that every move preserves (parity, sum mod k, XOR, the order of some subset) or always changes in one direction (a monovariant). It settles reachability or the winner in O(1) and replaces search.
Learn firstMath / Number Theory
0%
mastery
0/10 solved
0/10 solved
Recognise it
The signal
'is it possible to reach ...' where each move changes two things at once
1Brute force
BFS/DP over the state space.
2The observation
The size of the state space.
3Why it works
If the invariant differs between start and target, the target is unreachable; a construction shows the condition is also sufficient.
Reach for it when
- +moves by 2 are free, moves by 1 cost 1
- +a two-player game with a short closed-form answer
- +a huge state space or n up to 1e9
Not when
- ×the invariant is necessary but not sufficient (prove sufficiency or construct)
Practice
0/10 solved
- Minimum Cost to Move Chips to The Same PositionEasy
- Coin PilesCSESEasy
- Trouble SortCodeforces1300
- Range Addition IIEasy
- Global and Local InversionsMedium
- Minimum Moves to Equal Array ElementsMedium
- Stone GameMedium
- Chalkboard XOR GameHard
- Another GameCSESHard
- Minimum Time to Visit a Cell In a GridHard
Pitfalls
Misconceptions
- !stopping at necessity; a full proof needs a construction for the other direction
Go deeper1 combinations · resources
Combinations
Dijkstra (Weighted Shortest Path)+Invariants & Parity Arguments
grid with per-cell earliest-entry times where you may not stand still
- Dijkstra (Weighted Shortest Path):
- earliest arrival time per cell
- Invariants & Parity Arguments:
- waiting is only possible by stepping back and forth, which adds 2, so the arrival parity is fixed