Canonical Abstract Pattern Template
Review the archetype skeleton and test your memory retrieval.
We strongly advise reading through the rest of this page firstβespecially Core Intuition, Real-World Story, and Decision Rules belowβto build your mental model before revealing the pattern template.
- Pattern Overview & Core Intuition
Core Invariant & Operational Mechanism
Binary search is not "an algorithm for finding a number in a sorted array." It is a decision procedure: you have a range of candidate answers, you can ask one yes/no question about the middle candidate, and the answer to that question is guaranteed to tell you which half of the range to throw away. Because you throw away half every time, a range of one million candidates is exhausted in about twenty questions instead of one million.
The one thing that must be true for this to work is monotonicity: as you move from left to right across the candidate range, the answer to your yes/no question flips from No to Yes exactly once and never flips back β [No, No, No, Yes, Yes, Yes]. If the answers can flip back and forth, discarding a half is unsound and the whole method collapses. Sortedness is just the most common way monotonicity shows up; it is not the requirement itself.
What an invariant is (this term recurs in every pattern, so it is worth one definition): an invariant is a statement that is true before the loop starts, still true after every single pass, and therefore true when the loop ends. It is how you prove code is right without running it β and in an interview, stating your invariant out loud is worth more than the code itself, because it shows you know why the algorithm terminates with the right answer rather than that you remember its shape.
π£οΈ At every moment, if an answer exists at all, it lies inside [left, right]. Every branch I take preserves that.π‘ Don't worry if this feels abstract right now! Backtracking is one fundamental 3-move loop applied across different search spaces. As you progress through the 9 Archetype Variants (from Phone Numbers to Coin Change and Word Break), each hands-on challenge will cement this intuition until writing path.append() and path.pop() becomes second nature.