12 Coding Interview Patterns That Cover Most Questions
Learn the 12 problem-solving patterns behind most coding interview questions, from two pointers to dynamic programming, with how to spot each one and a template to start from.
LiveHint.ai team · · 5 min read
There are thousands of practice problems out there, and grinding through them at random is the slowest way to prepare. Most coding interview questions are variations on a small set of patterns. Learn to recognize the pattern and you're most of the way to a solution, even for a problem you've never seen.
Here are 12 patterns worth knowing, how to spot each one, and the core idea behind it.
1. Two pointers
Spot it: a sorted array or string, and you need to find a pair, remove duplicates, or compare from both ends.
Idea: keep two indices, often at opposite ends, and move them toward each other based on a comparison. That replaces an O(n²) nested loop with an O(n) pass.
Classic problems: pair with a target sum in a sorted array, valid palindrome, container with the most water.
2. Sliding window
Spot it: "longest", "shortest" or "maximum" over a contiguous subarray or substring.
Idea: grow the window by moving the right edge, and shrink it from the left whenever it breaks the condition. Track the state of the window in a hash map or counter.
def longest_without_repeats(s: str) -> int:
last_seen, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1
last_seen[ch] = right
best = max(best, right - left + 1)
return best
3. Fast and slow pointers
Spot it: linked lists or sequences where you need to detect a cycle or find the middle.
Idea: one pointer moves one step at a time and the other moves two. If there's a cycle they meet; if not, the fast one reaches the end while the slow one is at the middle.
Classic problems: linked list cycle, middle of a linked list, happy number.
4. Hash maps for counting and lookup
Spot it: "find whether something has been seen", frequencies, anagrams, or the complement of a value.
Idea: trade memory for time. Store what you've seen so each lookup is O(1).
Classic problems: two sum, group anagrams, top-k frequent elements.
5. Binary search, including on the answer
Spot it: sorted input, or a question like "the minimum X such that a condition holds" where the condition is monotonic.
Idea: halve the search space each step. The less obvious version searches over the answer: guess a capacity, speed or size, check whether it works, and narrow the range.
Classic problems: search in a rotated array, find the first bad version, minimum shipping capacity to deliver within D days.
6. Prefix sums
Spot it: many queries about sums over ranges, or "subarray sums to K".
Idea: precompute running totals so any range sum is a subtraction. Combined with a hash map of prefix sums seen so far, it counts subarrays with a given sum in O(n).
7. Monotonic stack
Spot it: "next greater element", "previous smaller element", or spans and areas in histograms.
Idea: keep a stack that stays increasing (or decreasing). When a new element breaks the order, pop. Each pop resolves the answer for the popped element.
Classic problems: daily temperatures, largest rectangle in a histogram, stock span.
8. Heaps for top-k and merging
Spot it: "k largest", "k closest", "running median", or merging k sorted lists.
Idea: a heap of size k keeps the best k items seen so far in O(n log k). Two heaps, one for each half, track a running median.
9. Intervals
Spot it: meetings, bookings, ranges that overlap.
Idea: sort by start time, then sweep through once, merging or counting overlaps. For "how many rooms do we need", process start and end events in time order.
Classic problems: merge intervals, insert interval, meeting rooms II.
10. Tree and graph traversal (BFS and DFS)
Spot it: trees, grids, networks, dependencies.
Idea: use BFS with a queue for shortest paths in unweighted graphs and level-by-level work; use DFS with recursion or a stack for exploring every path, connected components and most tree problems. Always track visited nodes in graphs.
Classic problems: number of islands, binary tree level order traversal, clone graph, course schedule (topological sort).
11. Backtracking
Spot it: "all combinations", "all permutations", "all valid arrangements", or constraint puzzles.
Idea: build a candidate step by step, recurse, and undo the last choice when you return. Prune branches that can't lead to a valid answer.
def subsets(nums):
result, current = [], []
def build(start):
result.append(current[:])
for i in range(start, len(nums)):
current.append(nums[i])
build(i + 1)
current.pop()
build(0)
return result
12. Dynamic programming
Spot it: "how many ways", "minimum cost", "maximum value", where choices overlap and the problem breaks into smaller versions of itself.
Idea: define what dp[i] (or dp[i][j]) means in words, write the recurrence, set the base cases, then decide on top-down memoization or a bottom-up table. Most interview DP problems fall into a few families: 1D sequences (house robber, climbing stairs), knapsack, two strings (edit distance, longest common subsequence) and grids (unique paths).
How to practice patterns efficiently
- Learn one pattern at a time. Solve three to five problems from the same pattern in a row, so the template sticks.
- Then mix them. Once you know several patterns, practice random problems. Identifying the pattern is the real interview skill.
- Say the pattern out loud. In the interview, "this looks like a sliding window because we need the longest contiguous substring" shows the interviewer how you think.
- Always state complexity. Give time and space for your approach before you code, and again at the end.
- Revisit what you missed. Keep a short note for each problem you couldn't solve: the pattern, and the insight you missed. Review it before your interview.
A simple way to approach any problem in the interview
- Restate the problem and ask about edge cases and input sizes.
- Give a brute-force idea and its complexity, in one sentence.
- Name the pattern that improves it, and explain why it fits.
- Code it cleanly, talking through key decisions.
- Test with a normal case and an edge case, then state the final complexity.
Interviewers care about that process as much as the final code. For design rounds, see our system design interview framework.
Keep reading
6 min read
The STAR Method: How to Answer Behavioral Interview Questions (With Examples)
A practical guide to the STAR method for behavioral interviews: what interviewers listen for, how to structure each part, and full example answers for engineers.
- #behavioral-interview
- #STAR-method
- #interview-tips
- #software-engineering
5 min read
A Step-by-Step Framework for System Design Interviews
A practical 45-minute framework for system design interviews: clarifying requirements, estimating scale, high-level design, deep dives and trade-offs, worked through on a URL shortener.
- #system-design
- #interview-tips
- #software-architecture
- #software-engineering