Back to Blog
Coding PatternsDSAInterview Tips

How to Identify Coding Interview Patterns in Four Reads

Amit Singh

Amit Singh

Author

August 11, 2026
12 min read

Knowing that seventeen patterns exist is one skill. Working out which one is in front of you, in ninety seconds, with someone watching, is another — and almost nobody practises the second directly.

The complete coding interview patterns guide is the companion to this post — it lists the patterns, the signal that identifies each, and the complexity to quote. Read it first if you are still building the vocabulary. This post assumes you have it, and answers the question that actually decides interviews: what do you physically do, at the desk, when the problem is unfamiliar?

Four reads of the same statement, in this order, because each narrows the field for the next: the constraints give you a complexity budget, the output shape gives you a family, the structure under the story gives you a candidate, and a disambiguation rule makes you commit.

Read 1: the constraints, before anything else

The constraints are the highest-information sentence in the problem, and most candidates skim past them to the narrative. Read them first: they tell you what complexity you may spend, which eliminates patterns before you have understood the problem at all.

The bridge from a constraint to a complexity is a planning figure: assume roughly 10⁸ simple operations per second. Be clear about what that number is. It is not a measurement and not a property of any machine you will run on — it is an order-of-magnitude convention for judging whether an approach is in the right league, and real throughput varies either way by a factor of ten depending on language, memory access pattern, and what "simple operation" means. As a rough divider it is reliable; as a precise budget it is nonsense.

With that convention, run the arithmetic backwards from n:

When n is the size of a collection — the length of the array, the number of nodes:

Constraint on nBudget it impliesWhat that admits
n ≤ 20O(2ⁿ), O(2ⁿ·n)Backtracking, bitmask DP, subset enumeration
n ≤ 10 or 11O(n!)Full permutation search — and only here
n ≤ 400O(n³)Interval DP, Floyd–Warshall, triple loops
n ≤ 5,000O(n²)Pairwise DP, edit distance, the quadratic LIS
n ≤ 10⁵ – 10⁶O(n log n) or O(n)Sorting, sliding window, two pointers, heap, prefix sum, traversal

When n is the magnitude of a number — a target value, an upper bound to search, an exponent. Nobody hands you an array of 10¹⁸ elements; these rows are about searching a range, not walking a collection:

Constraint on nBudget it impliesWhat that admits
n ≤ 10⁹O(log n), O(√n)Binary search on the answer, number theory
n ≤ 10¹⁸O(log n)Binary search, matrix exponentiation, digit DP

Do the arithmetic in your head or the read is worthless. At n = 10⁵ a quadratic is 10¹⁰ operations — about a hundred seconds at the convention, so two nested loops over the input are out of the league entirely. At n = 5,000 that same quadratic is 2.5 × 10⁷, a fraction of a second, so the nested loop is probably the intended solution and reaching for something cleverer wastes interview time.

Note the second row, which the round-number version of this advice gets wrong. "n ≤ 20 means exponential is fine" holds for 2ⁿ, about a million at n = 20. It does not hold for n!, which at 20 is around 2.4 × 10¹⁸; factorial search survives only to roughly n = 11 — and 11 only if the work per permutation is trivial, since generating them costs n!·n, which at 11 is already 4.4 × 10⁸. A bound of 20 points at subsets or bitmask states, not permutations.

The cubic row is the one worth arguing about, and it is where the convention's slack shows. You will see n ≤ 500 quoted for O(n³), but 500³ is 1.25 × 10⁸ — over the line by a quarter. It survives in practice because triple loops have tiny constants, which is precisely the ±10× wobble in the 10⁸ figure. I have written 400 because a divider you can trust beats one you have to make excuses for; if a problem hands you n ≤ 500 and a cubic idea, take it, but know you are spending the slack rather than staying inside the budget.

The inverse read matters too: an oddly small constraint is an instruction. Nobody bounds an array at 18 unless they want its subsets enumerated.

Read 2: the shape of the output

Now read what you are asked to return, in isolation from how you would compute it. Output shape rules whole families in and out, and it catches people who spotted the structure correctly but attached the wrong algorithm to it.

The problem returns…Rules inRules out
A single optimum (max/min value)DP, greedy, sliding window, binary search on the answerEnumeration
A count of ways or arrangementsCounting DP, combinatorics, prefix-sum countingGreedy
Every valid arrangement, listedBacktrackingEverything polynomial
A boolean — does one exist?Feasibility DP, traversal, union find, binary searchBuilding the full answer set
The k best of somethingHeap, quickselectA full sort, usually
An index, a pair, or a rangeTwo pointers, sliding window, binary searchApproaches that lose positions
The minimum number of stepsBFSDFS, greedy
A valid orderingTopological sort, sort-and-sweepUnordered set structures

The third row carries the strongest single signal in the method, and candidates apologise for it instead of using it. If the problem asks you to return every subset, every permutation, or every valid board, the output itself is exponential in size. No algorithm can be faster than the volume of what it must print, so exponential here is the correct answer and the only thing left to tune is the pruning — not knowing that costs four minutes hunting for a polynomial solution that provably cannot exist.

Read 3: strip the costume off the story

Problems arrive dressed. Daily closing prices, server heartbeats, building heights on a skyline — the same three or four structures in different clothes, and the clothes are what change between the practice problem and the interview.

The mechanical way to undress one, in about fifteen seconds:

  1. Replace every domain noun with a neutral one. Prices, heartbeats, buildings, transactions → items in a sequence. Cities and flights, users and follows, courses and prerequisites → nodes and edges.
  2. Reduce the goal verb to one of six. Maximise, minimise, count, list, decide, locate. The narrative hides it behind phrasing like "determine the best allocation" — that is minimise.
  3. Keep only the words that constrain the answer. Contiguous, distinct, at most, exactly, sorted, non-negative, in order, without repeating. Those are load-bearing; almost nothing else is.

What survives is a one-line problem you can classify. "Given the daily prices of a stock, find the longest stretch of days over which total volatility stays under a threshold" becomes given a sequence of non-negative items, find the longest contiguous range whose sum is at most S — a sliding window, before you have thought about stocks at all.

The same trick makes you immune to a trap in the other direction: words that look like signals and are not.

The wordWhat it looks likeWhen it is a false friend
"sorted"Two pointers / binary searchIf it describes the output order rather than the input, it buys nothing
"shortest"BFSOn a weighted graph it is Dijkstra; BFS needs every edge to cost 1
"maximum"GreedyMost maxima over sequences of choices are DP; greedy needs a justification
"all"Backtracking"All pairs summing to k" is a hash map; enumerate only if the answer set is exponential

Read 4: the disambiguation rules

After three reads you are usually down to two candidates rather than seventeen. These are the pairs that recur, and each resolves by rule rather than feel.

Dynamic programming vs greedy. If you cannot state the exchange argument in one sentence, it is DP. An exchange argument says any optimal solution can be transformed into the one your greedy rule produces without getting worse — for interval scheduling, "swapping the first meeting of any optimal schedule for the earliest-ending one can never create a conflict it did not already have." One sentence, and checkable. "It worked on the examples" is a coincidence, not an argument, and the interviewer already knows the counterexample. Default to DP; greedy is earned.

BFS vs DFS. A question about distance, or the minimum number of steps, is BFS, however tree-shaped the problem looks. This is the most common misclassification I see. A grid, a maze, a word ladder or a state space makes DFS feel natural because recursion is easy to write — but DFS finds a path, not the shortest, and patching that afterwards costs more than starting over. Classify on the output shape, not the structure. The caveat that earns a mark: BFS is only shortest when every edge costs the same, so weighted edges mean Dijkstra. Both traversals: graph algorithms.

Sliding window vs prefix sum. A window is legal only if shrinking from the left can restore validity. That needs the tracked quantity to move in one direction as the range grows, which non-negative values give you. Negatives destroy that, and nothing recovers it — growing the range can lower the sum, so exceeding the target tells you nothing about which edge to move. That is the real switch to prefix sums with a hash map.

An exact target is a lighter injury, and it is worth separating the two because most write-ups (including an earlier version of this one) lump them together. Exactness does not break monotonicity; it breaks downward-closure — a valid range can contain no valid sub-range, so there is no "shrink until it becomes valid" step. You buy that back by solving the at-most version twice and subtracting: over non-negative values, the number of ranges summing to exactly S is atMost(S) − atMost(S − 1), and both halves are ordinary windows. The same reformulation is what turns "exactly K distinct" into two window passes — see the sliding window in depth. So: negatives force the hash map; exactness only forces you to run the window twice.

Backtracking vs DFS. Are you exploring the input, or the candidate answers? DFS walks a structure that already exists and marks each node visited once, precisely so it never returns. Backtracking walks a decision tree that does not exist until you build it — so it undoes state on the way back up, and one element legitimately appears on many branches. Same recursion skeleton, opposite bookkeeping: a visited set never cleared, versus a choose/un-choose pair.

A worked pair: same costume, different pattern

Two problems dressed identically: both about an array, both saying contiguous, both mentioning a sum and a target. Under the four reads they are not the same pattern.

Problem A. A monitoring service records the number of dropped packets per minute over a window of n ≤ 10⁵ minutes, all values non-negative. Find the length of the longest run of consecutive minutes whose total drops are at most S.

Problem B. The same service records the net change in queue depth per minute over n ≤ 10⁵ minutes; values may be negative. Count how many runs of consecutive minutes have a net change of exactly S.

Read 1 is identical for both: n ≤ 10⁵ forbids the quadratic scan over all pairs of endpoints (10¹⁰ operations), so both need one linear-ish pass. It does not separate them, but it kills the brute force for both before you start.

Read 2 separates them immediately. A asks for a single optimum, a length. B asks for a count. Optimum-over-a-range points at a window; counting occurrences over ranges points at something that accumulates, which in practice means prefix sums with a frequency map.

Read 3 finds the load-bearing words: A carries non-negative and at most, B carries may be negative and exactly. Those four words are the entire problem — the packets and queues are costume.

Read 4 applies the rule. In A the sum only grows as the range grows, so when it exceeds S advancing the left edge is guaranteed to help: sliding window, O(n). In B the negatives are what decide it — with them, exceeding S no longer tells you which edge to move, and no shrink condition exists at all. Running totals plus a hash map of how often each total has been seen answers it in one pass instead. Note that exactly is not what disqualifies the window here: strip the negatives from B and it goes back to being two window passes. The word doing the work is may be negative.

Same clothes, four sentences of reading, no ambiguity — and no attempt to recall a similar problem.

Often Read 2 settles it on its own. Same grid, same story: "fewest moves for a robot to reach the dock in a 1000 × 1000 grid" is a distance question — BFS over 10⁶ cells — while "how many distinct routes reach it moving only right or down" is a count over overlapping subproblems, so dynamic programming.

When nothing fires

Sometimes all four reads land nothing. That is a cue to switch methods, not a recognition failure — staring harder has a poor success rate under pressure.

Write the brute force and say its complexity out loud. Then name the waste in one phrase. Waste is far easier to see than structure, and each kind has a short list of structures that remove it:

The brute force is wasting time on…Which is removed by
Recomputing an aggregate over a moving rangeSliding window, prefix sum
Re-deriving the same subproblemMemoisation, then DP
Rescanning forward for "the next larger thing"Monotonic stack, heap
Rechecking pairs when the data is orderedTwo pointers, binary search
Re-exploring nodes already reachedVisited set, union find
Re-sorting, or sorting when order does not matterHash map, counting

The ladder is also the best thing to say aloud while you think: "the brute force is O(n²) because I recompute the window sum at every start position, so the recomputation is the waste" is a candidate solving the problem in front of the interviewer, not one hoping to remember it.

How to practise the read itself

Recognition is trained by being wrong quickly. Re-solving problems you have already seen trains recall instead — which feels identical while you practise and diverges completely in the interview.

Classify without solving. Open a problem, spend the same ninety seconds you would get in the interview, write down four things: the complexity budget the constraints imply, the output shape, the pattern you commit to, and the signal that made you commit. Then check the editorial without writing code. Twenty problems fit in the time one full solve takes, and you are drilling the exact step that fails under pressure.

The fourth field does the work. "Sliding window" is not a signal; "contiguous, non-negative, longest-such-that" is. If you cannot fill it, you pattern-matched on the surface story — which is exactly what changes between practice and the interview.

Log the misses and read the log as a diagnosis. Every misclassification goes in a table: what you guessed, what it was, the signal you failed to see. After thirty or forty entries it becomes a study plan, because the errors cluster — and each cluster means something specific:

  • Guessed greedy, was DP → you are accepting exchange arguments you cannot state. Write the sentence before committing.
  • Guessed DFS, was BFS → you are classifying on structure instead of output shape. Read the ask before the input.
  • Guessed sliding window, was prefix sum → you skipped the constraint line. The word was "negative".
  • No guess at all → not a recognition failure but a vocabulary gap. Go and learn the pattern.

Mine cluster in the first two rows, consistently. Yours will cluster elsewhere, and where they cluster beats any generic problem list, because it is measured on you.

To schedule the classification passes against a date rather than doing them ad hoc, the free study-plan generator lays them out alongside the solving sessions.

The short version

Constraints give a complexity budget. Output shape gives a family. Stripping the story gives a candidate. Then one rule commits you: no exchange argument means DP, a distance question means BFS, negatives mean prefix sums rather than a window, building candidates rather than walking structure means backtracking. If nothing fires, name the waste in the brute force instead.

None of this needs you to have seen the problem before, which is the whole point — recognition that depends on familiarity fails exactly when it matters.

Doing this out loud, with someone pushing back on the signal you named, is the part that is hard alone — it is what the weekly sessions in the DSA course are built around, and nobody writes code before naming the signal.

Get the next pattern breakdown by email — one post, no filler.

Amit Singh works on distributed systems as a Senior SDE at Amazon and holds the Claude Certified Architect credential. He runs the DSA cohort at AlgoEngineer.

Frequently asked questions

What do the constraints tell me about which algorithm to use?
They tell you the complexity you are allowed to spend, which eliminates most patterns before you have thought about the problem at all. Using a planning convention of roughly 10^8 simple operations per second, n up to 20 means an exponential search is acceptable, n up to about 5,000 means O(n²) fits, n in the 10^5 to 10^6 range means you need O(n log n) or better, and an n near 10^18 means the answer must be O(log n) or pure arithmetic. Working backwards from that budget is the fastest single filter available.
How do I tell a sliding window problem from a prefix sum problem?
A window is only sound when shrinking it from the left can restore validity — which needs the tracked quantity to move in one direction as the range grows. Non-negative values give you that. Negatives destroy it: growing the range can lower the sum, so exceeding the target no longer tells you which edge to move, and that is the point where you switch to prefix sums with a hash map. An exact-equality target is a different and milder problem — it does not break monotonicity, only downward-closure, and you recover it by solving the at-most version twice and subtracting, since the count of ranges summing to exactly S is atMost(S) minus atMost(S-1). Negatives force the hash map; exactness only forces two window passes.
What is the difference between backtracking and DFS?
DFS traverses a structure that already exists and marks each node visited once. Backtracking traverses a decision tree that you are building as you go, which is why it undoes state on the way back up and why the same underlying element can appear on many different branches. Ask what you are exploring: if it is the input, that is DFS with a visited set; if it is the set of candidate answers, that is backtracking with an un-choose step.
Can I train pattern recognition without solving every problem end to end?
Yes, and separating the two is the point. Read a problem, write down the pattern you think it is and the specific signal that made you think so, then check against the editorial without writing code. A classification pass takes about ninety seconds, so you can cover twenty problems in the time one full solve takes. Solving trains implementation; classifying trains the read, and the read is what fails in interviews.
What should I do if I read a problem and no pattern comes to mind at all?
Stop hunting for the pattern and write the brute force with its complexity out loud. Then name the specific waste in one phrase — recomputing an aggregate, re-deriving a subproblem, rescanning for the next larger element, re-exploring a node. Each kind of waste has a small set of structures that remove it, so naming the waste narrows the search far more reliably than staring at the statement waiting for recognition to arrive.

Ready to Ace Your Interviews?

Live, cohort-based interview prep taught by a working FAANG engineer — weekly mock interviews, lifetime access, and a 7-day money-back guarantee.