Coding Interview Patterns

Course Content

Coding Interview Patterns

20 sections · 146 lessons

Recognising the Pattern: A Checklist and a Decision Tree


Most candidates who fail a coding round do not fail at coding. They fail in the first five minutes, when they do not know what kind of problem they are looking at and start typing a brute force they cannot improve.

Recognition is a skill you can practise directly. It has two parts: a short checklist you run on every problem, and a map from the signals you find to the patterns in this course. The map gives you a candidate, not a verdict — you still confirm it by checking that the pattern's mechanism really applies. But a candidate in the first minute changes the whole interview.

Six questions that name the patternWhichpattern is this?Is the input sorted?Contiguous subarray?Seen this before?Top or smallest K?All combinations?Optimal over choices?
Most problems answer yes to exactly one of these, and the answer names the pattern.

The six questions

Ask them in this order. Each one takes seconds.

1. Is the input sorted — or can I sort it cheaply? Sorted input is a loud signal. It points at binary search or two pointers. If the input is not sorted but the answer does not depend on the original order, sorting costs O(n log n) and may unlock a much simpler solution. That is the whole opening move of the Intervals section and of 3Sum.

2. What is the shape of the data? A flat sequence points at two pointers, sliding windows, prefix sums or stacks. A chain of nodes points at linked-list techniques. A hierarchy points at trees. Things with relationships — including grids, which are graphs in disguise — point at graphs. Many strings that share beginnings point at tries.

3. Contiguous, or any selection? "Subarray" and "substring" mean contiguous, which points at sliding windows or prefix sums. "Subsequence" and "subset" mean any selection that keeps the order, which points at dynamic programming or backtracking. The words look similar and lead to completely different solutions; misreading one for the other is a common way to lose twenty minutes.

4. Best answer, all answers, or a count? "Maximum", "minimum", "the fewest" point at optimisation: greedy or dynamic programming. "Find all" or "return every" point at backtracking. "How many ways" points at dynamic programming, or at counting with a hash map.

5. What is the brute force, and what does it repeat? Always write this down. Every pattern in this course repairs a specific repeated computation. A nested loop re-scanning the same array → two pointers or a hash map. Recomputing the sum of overlapping ranges → a sliding window or prefix sums. Recursive calls with arguments you have seen before → memoisation.

6. What do the constraints permit? Use the table from What the Constraints Tell You. It removes candidates fast: at n = 10⁵, anything quadratic is gone.

Questions 3 and 5 do most of the work. "Contiguous or not" and "what is repeated" between them identify the pattern for a large share of problems.

Two worked reads

The decision tree

After the checklist, walk the tree from the top. Its first split is the shape of the data, because that single fact removes most patterns at once.

New problemwhat is the input?Array or stringTwo Pointerssorted, or sortableL2Binary Searchsorted, or a monotonic answerL7Sliding Windowcontiguous subarray or substringL6Prefix Sumsrange sums over a static arrayL11Hash Maps & Setsseen it / count it / group itL3Stacksnext greater, nesting, matchingL8Heapstop K, k-th largest, streaming medianL9Intervalspairs of start and end valuesL10Bit Manipulationbits, subsets of a small setL19Linked listLinked Listsreorder, reverse, merge, spliceL4Fast & Slow Pointerscycle, middle, O(1) spaceL5TreeTrees / DFSanswer at a node needs its childrenL12Trees / BFSlevel by level, or shortest depthL12Triesmany strings sharing prefixesL13Graph, grid, or relationshipsBFSshortest path, unweightedL14DFSreachability, path enumerationL14Topological Sortdependencies and orderingL14Union-Findgrouping and merging setsL14Dijkstraweighted shortest pathL14No obvious structure — a choice problemBacktrackingfind ALL arrangements, n ≤ 20L15Dynamic Programmingmax/min/count and subproblems repeatL16Greedyone local choice is provably safeL17Math & Geometrynumbers, matrices, coordinatesL20Constraint shortcutsn ≤ 20exponential is finen ≤ 500O(n³) passesn ≤ 5,000O(n²) passesn ≤ 10⁵O(n log n)n ≤ 10⁶O(n) onlyn ≤ 10⁹binary search or mathsCommon compositionsHash map+sliding windowHash map+prefix sumsSort+greedyTrie+backtrackingEvery leaf carries its lesson number, so the treestill works printed in black and white.
Start from the input shape, not the problem statement — the input narrows twenty patterns to two or three.

If the diagram is not in front of you, here is the same map in list form, covering all nineteen patterns in this course. The last column is what the pattern removes from the brute force — the reason it is faster.

Signal in the problemFirst candidateWhat it stops you repeating
Sorted array or string; find a pair or triplet; mirror check; rearrange in placeTwo PointersRe-pairing every element with every other
"Have I seen this?"; count, group, or pair up values in unsorted inputHash Maps and SetsLinear scans to look something up
Reverse, merge, reorder or split a chain of nodesLinked ListsCopying nodes into an array and back
Cycle, middle of a list, k-th from the end, O(1) space on a sequenceFast and Slow PointersStoring visited nodes to spot a revisit
Longest or shortest contiguous run meeting a conditionSliding WindowsRecomputing overlapping ranges from scratch
Sorted data, find a position; smallest value that "works" over a huge rangeBinary SearchChecking every position or every candidate answer
Brackets, nesting, undo; next greater or smaller elementStacksScanning back over elements already passed
Top k, k-th largest, running median, "always take the smallest next"HeapsRe-sorting after every insertion
Start and end pairs: meetings, bookings, ranges that overlapIntervalsComparing every range with every other
Many range-sum queries; count subarrays with a given sumPrefix SumsRe-adding the same elements for each range
A hierarchy where a node's answer depends on its childrenTreesRe-walking subtrees you already solved
Many words sharing prefixes; autocomplete; word search over many wordsTriesComparing each query against every word
Entities and links, grids, shortest path, prerequisites, connectivityGraphsRe-visiting nodes without a visited set
"Return all" combinations, permutations or placements; n ≤ 20BacktrackingBuilding invalid candidates to the end
"Max, min or how many ways" where choices create repeated subproblemsDynamic ProgrammingSolving the same subproblem again and again
A locally best choice that you can prove never hurtsGreedyExploring choices you can prove are worse
Sorting unlocks the problem; custom order; k-th element; small value rangeSort and SearchComparing unsorted items blindly
Single odd element, subsets as bit masks, powers of two, parityBit ManipulationExtra memory to record flags or counts
n is a huge value; digits, divisors, gcd, modular arithmetic, points and rotationsMath and GeometrySimulating what a formula computes directly

Two rows deserve a warning. "Pair with a target sum" appears under both Two Pointers and Hash Maps: the tie-breaker is whether the input is sorted and whether you must return original positions. And "longest contiguous" under Sliding Windows needs the window's condition to change in one direction as it grows; when it does not (negative numbers in a sum), fall back to Prefix Sums.

Compositions: when one pattern gets you halfway

Many interview problems combine two patterns. Sliding window plus hash map is the most common pairing — the window gives the contiguous range, and the map tracks what is inside it. Sort plus greedy, sort plus two pointers, heap plus graph (shortest paths with weights) and binary search plus a greedy check are the others you will meet most.

So if one branch of the tree gets you halfway, take the halfway answer and re-enter the tree with what remains. "I have sorted the intervals — now I need the smallest end time among the open ones, quickly" is a second, smaller recognition problem, and it points at a heap.

When nothing fits

Sometimes the checklist gives you nothing. Then say the brute force out loud, write it down, and look at what it repeats. That almost always names the pattern. It also buys you something important: a working solution you can improve, and a clear story for the interviewer — "this is correct but O(n²); the inner loop keeps re-scanning the same values, so let me try to remember them instead."

Check your understanding

0 of 3 answered

1.A problem asks for the number of subsequences of a string that spell a given word. Which family should you consider first?

2.Given an unsorted array, return the original positions of two values that add up to a target. Why is "sort, then two pointers" a poor first choice?

3.You have sorted a list of intervals and now repeatedly need the earliest finishing time among the intervals still open. What does the decision tree suggest for the second half?