Interview prep
Coding interview patterns: 14 patterns, the signal for each, and a study order
Fourteen reusable patterns that cover most algorithm questions, the cue in the prompt that points to each one, two short Python samples and an order to study them in.
The HIDEA AI team
11 min read

Coding interview patterns are reusable problem-solving shapes, such as two pointers, sliding window or breadth-first search, that cover most algorithm questions. Learning them means learning the signal in a prompt that points to each one, so a new problem looks like a variation rather than a blank page. This guide lists 14 patterns, the cue for each, a typical problem, two short Python samples and a study order.
Why learn patterns instead of memorizing problems?
Interviewers change the wording, the constraints and the follow-up, so a memorized solution often breaks halfway through the round. A pattern survives the change. If you know that "longest contiguous stretch with a condition" points to a sliding window, a problem about characters, prices or sensor readings is the same problem.
Patterns also give you something to say in the first two minutes. "The input is sorted and I need a pair, so I'm thinking two pointers" shows how you reason before any code exists.
Array and string patterns
1. Two pointers
Signal: a sorted array or string, and a question about pairs, or about reversing or partitioning in place. Typical problem: in a sorted list, find two numbers that add up to a target. Start one pointer at each end, and move the left one up when the sum is too small and the right one down when it is too large. O(n) time, O(1) space.
2. Sliding window
Signal: the longest, shortest or count of contiguous subarrays or substrings that meet a condition. Typical problem: find the length of the longest stretch of a string with no repeated character. Grow the window on the right, and shrink it from the left when the condition breaks.
def longest_unique_substring(s):
last_seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # shrink past the repeat
last_seen[ch] = right
best = max(best, right - left + 1)
return best
print(longest_unique_substring("abcabcbb")) # 3
print(longest_unique_substring("abba")) # 2
print(longest_unique_substring("")) # 0Each character enters the window once, and the left edge only moves forward, so the run time is O(n). The check last_seen[ch] >= left matters: without it, a repeat that is already outside the window would wrongly move the left edge backwards, which is what the "abba" test catches. Sliding windows need the condition to behave predictably as the window grows. With negative numbers in a sum problem, that breaks, and prefix sums are the better tool.
3. Hash map counting
Signal: you need to know whether you have seen something before, how many times, or what it pairs with. Typical problem: find two numbers in an unsorted list that sum to a target, by storing each value's index and looking up target minus value. Also anagram grouping and first unique character. This trades O(n) memory for O(n) time instead of O(n²).
4. Prefix sums
Signal: many range-sum queries, or counting subarrays whose sum equals a value, especially when negative numbers rule out a sliding window. Typical problem: count the subarrays that add up to k. Keep a running total, and a hash map of how often each running total has appeared. At each position, the number of earlier totals equal to the current total minus k is the number of subarrays ending here.
5. Binary search on the answer
Signal: "find the minimum capacity, speed or time such that something is possible", where a larger value is always at least as feasible as a smaller one. Typical problem: the slowest eating speed that finishes all the piles within a deadline. Binary search over candidate speeds, and for each one run a quick check of whether it works. The check is usually O(n), so the total is O(n log range).
6. Stack and monotonic stack
Signal: matching pairs, such as brackets or tags, calls for a plain stack. "Next greater element", "days until a warmer temperature" or "largest rectangle" calls for a monotonic stack, which keeps its items in increasing or decreasing order. Typical problem: for each day, how many days until a warmer one.
def days_until_warmer(temps):
answer = [0] * len(temps)
stack = [] # indices whose warmer day is not found yet; temps decrease
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j
stack.append(i)
return answer
print(days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73]))
# [1, 1, 4, 2, 1, 1, 0, 0]The stack holds the indices of days still waiting for a warmer day, and their temperatures decrease from bottom to top. When a warmer day arrives, it resolves every cooler day on top of the stack. Each index is pushed once and popped at most once, so the whole thing is O(n), even though a while loop sits inside a for loop. Saying that sentence out loud heads off the "isn't that O(n²)?" question.
Data structure patterns
7. Heap or top-k
Signal: the k largest, k smallest, k most frequent or k closest items, or a stream where you repeatedly need the current minimum or maximum. Typical problem: return the k most frequent words. Keep a min-heap of size k and push each candidate, popping the smallest when the heap grows past k. O(n log k) time, which beats sorting when k is small.
8. Intervals
Signal: ranges with start and end points, such as meetings, bookings or time slots. Typical problems: merge overlapping intervals, or find the fewest rooms needed for a set of meetings. Sort by start time first. Merging then takes one pass. For room counts, a min-heap of end times tells you whether the earliest-ending meeting has freed a room.
9. Tries
Signal: prefix questions over many words, such as autocomplete, "does any word start with this", or finding many dictionary words in a grid of letters. Typical problem: build a structure that inserts words and answers prefix searches. Each node holds child links and an end-of-word flag. Lookups cost O(length of the word), whatever the dictionary size.
10. Union-find
Signal: groups that merge over time, connectivity questions, or edges that arrive one at a time. Typical problem: count the provinces in a network of cities given which pairs are directly connected, or find the one extra edge that creates a cycle. With path compression and union by rank, each operation runs in near-constant amortized time.
Search and optimization patterns
11. BFS and DFS
Signal: anything you can describe as nodes and edges, including grids, dependency lists and word transformations. Use BFS for the fewest steps when every step costs the same, and DFS for exploring regions, finding any path, and detecting cycles. Typical problem: count the islands in a grid of land and water. The graph algorithms interview questions guide covers topological sort, union-find and Dijkstra with code.
12. Backtracking
Signal: "return all" combinations, permutations, subsets or valid arrangements, usually with small inputs. Typical problem: list every subset of a set of numbers, or place queens on a board so none attack each other. Build a partial answer, recurse, then undo the last choice. Pruning invalid branches early is where most of the speed comes from. The output itself is often exponential, so say that up front.
13. Dynamic programming
Signal: a minimum, maximum or count of ways, built from a sequence of choices where the same partial state comes up more than once. Typical problem: the most money you can take from a row of houses without taking two neighbours. Define the state, write the transition, fix the base cases. Dynamic programming interview patterns walks through the five families with code.
14. Greedy
Signal: a local choice that never needs to be undone, often after sorting. Typical problem: pick the largest number of non-overlapping meetings, by always taking the one that ends earliest. Greedy solutions are short but easy to get wrong. Before committing, try to break your rule with a small counterexample. If you can, switch to DP.
How to pick a pattern in the first five minutes
You won't always recognise the pattern immediately. A short routine gets you there more often than staring does.
- Read the constraints. Input size narrows the target complexity. Around a hundred thousand elements usually rules out O(n²). Very small inputs, around twenty, make exponential search acceptable.
- Name the input shape. Sorted array, string, grid, list of edges, list of intervals, stream. Each shape has two or three likely patterns.
- Name the ask. One value, a count, all solutions, or a yes or no. "All" suggests backtracking. A count or optimum suggests DP or greedy.
- Say the brute force. One sentence and its complexity. It is a fallback and a baseline to improve on.
- Ask what repeats or what you're rescanning. Repeated work points to DP or a hash map. Rescanning a range points to a sliding window or prefix sums.
Worked example: choosing a pattern aloud
Here is an invented example of narration for "count the contiguous subarrays whose sum equals k", where the numbers can be negative.
"Brute force is every start and end, summing as I go, which is O(n²). My first thought was a sliding window, but negative numbers mean growing the window can make the sum smaller, so the window can't tell when to shrink. Instead I'll keep a running prefix sum. A subarray from i to j sums to k when the prefix at j minus the prefix before i equals k. So at each position I look up how many earlier prefixes equal the current one minus k, using a hash map of counts. I need to seed the map with zero seen once, for subarrays that start at index 0. That's O(n) time and O(n) space."
The candidate rejected one pattern with a reason, chose another, explained the key identity, and caught the base case before typing.
A study order for coding interview patterns
Order matters because later patterns lean on earlier ones. A reasonable sequence, roughly one or two patterns per study block:
- Hash map counting and two pointers. The most common building blocks. Many harder solutions use one of them inside.
- Sliding window and prefix sums. Learn them together so you know when each applies.
- Stack and monotonic stack. Short code, but the O(n) argument takes practice to say clearly.
- Binary search, including on the answer. Get the boundary conditions right once and reuse the template.
- Heap and intervals. Both often start with a sort and use a heap for the running state.
- BFS and DFS, then union-find and tries. Graphs build on the earlier data structures. Union-find and tries are smaller topics that fit after.
- Backtracking. It is recursion with undo. Learn it before DP, because top-down DP is backtracking plus a cache.
- Greedy, then dynamic programming. Last, because the hard part is proving a greedy choice or defining a DP state, and that comes easier once the other patterns are familiar.
If you have only two weeks, the two-week technical interview preparation plan shows how to fit this order around the rest of your preparation.
Common mistakes
- Matching on keywords alone. "Subarray" doesn't always mean sliding window. Check the condition, as the negative-numbers example shows.
- Skipping the brute force. Without it you have no baseline, no fallback, and nothing to compare your faster answer against.
- Studying silently. The round is spoken. A pattern you can code but not explain is half learned.
- Trusting greedy without a check. A short greedy answer that fails one hidden case scores worse than a slower correct one.
A practice loop for patterns
Spend each session on one pattern. Solve one problem aloud on a 25-minute timer: name the signal, say the brute force, choose the pattern, code it, test it, state the complexity. Afterwards, write one line describing the signal in your own words. Two days later, redo the problem from a blank editor. Once a pattern feels automatic, mix in problems where you don't know the category in advance, because recognising the pattern under pressure is the skill being tested.
The narration habit is the part most people skip. Live coding mock interview: narrate under a timer explains how to rehearse it.
Practice patterns on the Live coding surface
HIDEA AI has four separate surfaces: Verbal, Live coding, System design and Project. Pattern practice belongs on Live coding. You capture a problem from the screen, and the response leads with a plain-English approach, then code in the language you picked, then time and space complexity.
The useful way to practice is to commit first: say which pattern you think fits and why, write your solution, then compare your choice and complexity with the response. You still speak or type every answer. Fifteen session minutes a day is free, with no credit card, on the macOS and Windows desktop app. See the interview copilot overview and the pricing page.
For how the surface behaves in a real round, read how to use an interview copilot in a live coding round. Before using any tool in a live round, check the employer's rules, and see is using an AI interview copilot cheating for how to separate practice from the real thing.
Where to go next
- Go deeper on the hardest family: dynamic programming interview patterns.
- Graphs, with runnable code: graph algorithms interview questions.
- Get ready for a timed test: online coding assessment prep.
- Download the app and practice one pattern today.
Frequently asked questions
How many coding interview patterns do I need to know?
Around a dozen to fifteen covers most algorithm questions: two pointers, sliding window, hash maps, prefix sums, binary search, stacks, heaps, intervals, tries, union-find, BFS and DFS, backtracking, dynamic programming and greedy. Knowing the signal for each one matters more than adding more patterns to the list.
Are LeetCode patterns enough to pass a coding interview?
Patterns help you find an approach, but interviews also score how you communicate, test and handle follow-ups. Practice explaining your choice aloud, writing clean code under a timer, testing edge cases and stating complexity. Patterns without that practice tend to fall apart when the interviewer changes a constraint.
What order should I learn coding interview patterns in?
Start with hash maps and two pointers, then sliding window and prefix sums, stacks, binary search, heaps and intervals, graphs, backtracking, and finally greedy and dynamic programming. Earlier patterns appear inside later solutions, and DP is easier once backtracking and recursion feel natural.
How do I recognise which pattern a problem needs?
Read the constraints to estimate the target complexity, name the input shape, and name what the question asks for. Then say the brute force and ask what it repeats or rescans. Repeated work points to DP or a hash map, and rescanning a range points to a sliding window or prefix sums.



