How to Think in Algorithm Patterns
Strong problem solvers do not reinvent algorithms from scratch for every question. Instead, they learn to recognize a small set of patterns and map new problems onto them.
In interviews, the difference between "I've seen this pattern" and "I'm starting from zero" is often the difference between finishing in 20 minutes vs. getting stuck.
This article gives you a mental model for:
- Classifying problems quickly.
- Picking a candidate pattern (e.g. [Sliding Window](/blog/algorithms/sliding-window/sliding-window-basics), [Two Pointers](/blog/algorithms/two-pointers/when-to-use-two-pointers), Heap / Top K, DP).
- Iterating from brute force to a pattern‑based solution.
The Pattern Thinking Framework
A five-step mental model for mapping problems to patterns.
1Classify the input2Reach for a pattern3Start brute force4Apply template5Sanity-check
Step 1: Classify the Input and Question
Before writing code, answer three questions:
Key questions
- What is the main input structure?
- Array, string, linked list, tree, graph, matrix, stream, …
- What does the problem ask you to optimize or return?
- Min / max value, count, existence, path, subset, ordering, …
- What constraints matter most?
- Time (
nup to 1e5 or 1e6?), memory, online vs offline, number of queries, …
- Time (
Why it matters
This classification narrows down the likely patterns.
Step 2: Reach for Pattern Checklists
Here are some quick "pattern triggers". Use the grid below to pick one or two promising patterns to try first. The goal is not to guess the final solution immediately.
Sliding Window
When to useContiguous subarray/substring; min/max/count over a moving range.TriggerArray/string, contiguous, moving range.Two Pointers
When to useFind pairs/triplets, partition, or remove duplicates in-place.TriggerSorted array or something you can sort.Binary Search
When to useFind boundary (first true / last false) or search on answer space.TriggerMonotonic condition; minimum feasible value, smallest radius.Heap / Top K
When to useRepeatedly pick current best (min/max); top K, Kth largest/smallest, streaming.TriggerSet changes; need top K or streaming statistics.DFS / Backtracking
When to useExplore all configurations with constraints (subsets, permutations, combinations, paths). Natural recursion on "position" or "choice index".TriggerRecursion on position or choice index.BFS / Shortest Path (Unweighted)
When to useShortest number of steps / edges in an unweighted graph or grid.TriggerMinimum moves, minimum transformations.Dynamic Programming
When to useOverlapping subproblems, optimal substructure; optimization over sequences, knapsack-like.TriggerCounting structures; reuse subproblem results.Greedy
When to useLocal best choice leads to global optimum; often sorting + one pass.TriggerInterval scheduling, activity selection; convincing exchange argument.
Step 3: Start from Brute Force, Then Simplify
Key idea
For any nontrivial problem, it's fine to think:
- "What is the simplest brute‑force approach?"
Write it down conceptually, even if it'sO(n^3). - "Where is the redundancy or repeated work?"
That is where a pattern can help:- Sliding window: avoid recomputing sums/counts over overlapping ranges.
- DP: avoid recomputing subproblem results.
- [Heap](/blog/algorithms/heap-top-k/heap-fundamentals): avoid rescanning the whole array for the current best.
Why it matters
Most "optimized" algorithms are just structured memoization / reuse on top of a brute‑force idea.
Step 4: Use Pattern Templates
Each pattern has a template that you should memorize and be able to write quickly:
- [Sliding Window](/blog/algorithms/sliding-window/sliding-window-basics):
left,right, expand, shrink, update answer. - [Two Pointers](/blog/algorithms/two-pointers/when-to-use-two-pointers): advance
iand/orjbased on comparisons. - [Binary Search](/blog/algorithms/binary-search/binary-search-fundamentals): invariant on
[lo, hi]and a monotonic predicate. - BFS: queue + visited set, process layer by layer.
- DFS / Backtracking: recursion on
index, add choice, recurse, undo. - DP: define
dp[i]ordp[i][j], write transition, fill in order.
Why it matters
In an interview, you don't want to debug the template itself. You want all your brainpower on the problem‑specific parts (state, condition, transition), not on the skeleton.
Step 5: Sanity‑Check with Known Examples
When you map a problem to a pattern, ask:
Key question
"What is this most similar to, among the classic problems I know?"
- Longest substring without repeating chars → [Sliding Window](/blog/algorithms/sliding-window/sliding-window-basics).
- K closest points → Heap / Top K.
- Coin change / knapsack → DP.
- Interval scheduling / activity selection → [Greedy](/blog/algorithms/greedy/interval-scheduling).
Why it matters
Use those classics as anchors:
- Reuse their invariants.
- Reuse their DP states or window conditions with small adaptations.
When Patterns Are Not Enough
When Patterns Are Not EnoughPatterns are guides, not cages. Warning signs you might be forcing the wrong pattern: • Your code becomes **overly complicated** for something that sounds simple. • Invariants are hard to state or keep consistent. • You rely on many ad‑hoc conditions. In such cases: (1) Step back to the problem definition. (2) Re‑examine constraints and data types. (3) Consider switching patterns or combining two (e.g. [[Sliding Window](/blog/algorithms/sliding-window/sliding-window-basics)](/blog/algorithms/sliding-window/sliding-window-basics) + HashMap, [[Heap](/blog/data-structures/tree-structures/heap-min-max)](/blog/algorithms/heap-top-k/heap-fundamentals) + [**BFS**](/blog/algorithms/bfs-graph-traversal/bfs-fundamentals)).
How to Practice Pattern Thinking
To really internalize patterns:
- Pick a pattern (e.g. [Sliding Window](/blog/algorithms/sliding-window/sliding-window-basics)) and solve 5–10 related problems in a row.
- For each problem, explicitly write:
- Why this pattern fits.
- What the state / window / DP definition is.
- What the invariants are.
- After finishing, summarize what changed between problems and what stayed the same.
Over time, when you see a new question, your brain naturally asks:
"Is this just another variation of pattern X?"
That's when you're truly thinking in algorithm patterns, not memorizing individual problems.