10 Coding Interview Questions: Patterns, Traces, and Practice

Quick Overview
Practice ten coding interview patterns with worked traces, complexity assumptions, edge cases, and links to relevant algorithm questions.
Ten familiar problems can teach ten reusable patterns. The useful preparation is to explain why each approach works, trace it on a small input, and identify the contract that would change the answer.
This is a practice sequence, not a prediction of a company's next interview. For company-specific context, read the analysis of coding patterns in PracHub question data, including its sample limitations. The examples below are independent teaching examples; use the linked questions to practice variants with their own requirements.
Choose the pattern and state its cost
Here, n is the input length or node count, r and c are grid dimensions, A is the target amount, d is the number of coin denominations, m is the number of distinct values, and w is the widest tree level. Hash-based bounds assume well-distributed hashes. Space excludes the returned output unless stated otherwise.
| Question | Main idea | Time and working space |
|---|---|---|
| Two Sum | Remember earlier complements | Expected O(n) time; O(n) space |
| Longest unique substring | Maintain a valid sliding window | Expected O(n) time; O(min(n, alphabet size)) space |
| Merge intervals | Sort, then extend the current interval | O(n log n) time; sorting and copying space depend on implementation |
| Reverse a linked list | Preserve the next pointer before rewiring | O(n) time; O(1) iterative space |
| Number of islands | Traverse each connected component once | O(rc) time; O(rc) worst-case space |
| LRU cache | Hash map plus doubly linked recency list | Expected O(1) per get/put; O(capacity) storage |
| Tree level order | Process one queue layer at a time | O(n) time; O(w) queue space |
| Coin change | Minimum coins for each smaller amount | O(Ad) time; O(A) space |
| Trapping rain water | Establish the limiting boundary | O(n) time; O(1) space with two pointers |
| Top K frequent values | Count, then select among distinct values | Expected O(n + m log(k + 1)) time; O(m + k) space with a bounded heap |
1. Two Sum: what must the returned pair mean?
Ask whether the result contains indices or values, whether a solution is guaranteed, and whether any valid pair is acceptable. You cannot use the same index twice.
For the usual any-pair version, scan left to right. Before storing the current value, look for its complement among earlier values. With [3, 3] and target 6, the first value has no earlier partner; the second finds index 0, giving (0, 1). Looking up before inserting prevents matching a value with itself.
Invariant: every stored index belongs to an already processed element. Expected time is O(n), with O(n) storage. Sorting can support a two-pointer alternative, but returning original indices requires preserving them.
Tie-breaking changes the task. In [1, 2, 3, 4] with target 5, the first pair found by the ordinary scan is (1, 2), while the lexicographically smallest pair is (0, 3). Practice that stricter contract in Return the Lexicographically Smallest Two-Sum Index Pair. Do not assume the basic early-return approach satisfies it.
2. Longest substring without repeats: can the left boundary move backward?
Maintain a window containing no repeated character. A last-seen map lets you skip directly past a duplicate, but only when its previous position is inside the current window.
Trace abba: the first two characters form ab; the second b moves the left boundary to index 2. When the final a arrives, its previous index is outside the window. Moving left back to index 1 would incorrectly admit bba. Keep the new left boundary at least as large as the old one. The maximum valid length is 2.
Expected time is O(n), since each position is processed once. Define the unit being counted: bytes, UTF-16 code units, Unicode code points, and user-perceived characters are different contracts. An implementation that handles ASCII correctly does not automatically handle every Unicode requirement.
Try Find longest substring without repeating characters, then test an empty string, all identical characters, and a repeat that lies outside the current window.
3. Merge intervals: do touching endpoints overlap?
Sort intervals by start, then compare each interval with the last merged result. For closed intervals, [1, 3] and [3, 5] share an endpoint and merge. Thus [1, 3], [3, 5], [8, 10] becomes [1, 5], [8, 10].
Invariant: the merged prefix is sorted and disjoint. When intervals overlap, the new end is the larger end. Replacing it unconditionally with the next end fails for nested intervals such as [1, 10], [2, 3].
Clarify the boundary rule for half-open intervals and whether adjacent integer intervals without a shared endpoint should merge. Those are specification choices. Sorting costs O(n log n), and scanning costs O(n). The returned intervals can occupy O(n); sorting may also allocate auxiliary space, so “sort in place” is not enough to promise O(1) working memory.
Practice the specified closed-interval contract in Merge overlapping closed intervals into a sorted list of disjoint intervals.
4. Reverse a linked list: which reference must survive each step?
An iterative reversal maintains a reversed prefix and an unprocessed suffix. Save the current node's original successor before redirecting its next reference toward the prefix.
For 1 → 2 → 3, the prefix grows from empty to 1, then 2 → 1, then 3 → 2 → 1. If you overwrite the next reference before saving it, you lose the route to the remaining suffix.
The iterative approach takes O(n) time and O(1) auxiliary space. A recursive approach usually needs O(n) call-stack space and can exceed a language's recursion limit. Test an empty list and a single node, and confirm whether the input is guaranteed to be acyclic.
Use Reverse a linked list to practice pointer updates, then explain how the invariant changes when reversing only a subrange.
5. Number of islands: when does a cell become visited?
For four-directional adjacency, each previously unseen land cell starts one traversal and increments the island count. Mark a cell when adding it to a BFS queue, rather than waiting until removal, so multiple neighbors do not enqueue the same cell repeatedly.
This grid has three islands:
11000
10000
00100
00011
The upper-left cells form one component, the middle cell is another, and the bottom-right pair is the third. With diagonal adjacency, the middle cell connects diagonally to the bottom-right pair, changing the answer to two. State the adjacency rule before coding.
Traversal takes O(rc) time. A visited set, recursion stack, or BFS frontier can require O(rc) space in the worst case. Mutating the grid removes the separate visited set, but does not eliminate traversal storage. Ask whether input mutation is permitted.
Practice Solve Number of Islands, including all-water, all-land, and single-row cases.
6. LRU cache: what does a successful read change?
An LRU cache evicts the least recently used entry. A successful get changes recency, as does inserting or updating an entry. A hash map finds entries; a doubly linked list allows removing a known node and moving it to the most-recent end without scanning the list.
At capacity 2, trace these operations:
put(A, 1) -> A is most recent
put(B, 2) -> B is most recent
get(A) -> returns 1; A becomes most recent
put(C, 3) -> evicts B
get(B) -> miss
Expected get/put time is O(1), with O(capacity) storage. Replacing an existing value must not create a duplicate list node. Define capacity-zero behavior and the miss result explicitly.
The single-threaded structure is not automatically a concurrent cache. A concurrent design must keep map membership and list updates consistent across an entire operation. Practice Process LRU Cache Operations before adding expiration or concurrency requirements.
7. Binary tree level order: where does one level end?
Use BFS, recording the queue length at the start of a level. Process exactly that many nodes; their children belong to the next level. Rechecking a growing queue's current length as the level boundary can mix depths.
For a tree whose root is 1, children are 2 and 3, and node 2 has right child 4, the result is [[1], [2, 3], [4]]. An empty tree returns [].
Each node is processed once, giving O(n) time. The queue occupies O(w), where w is the maximum level width; the returned values require a separate O(n). Use a queue with efficient removal from the front, rather than repeatedly shifting an array-backed list.
Practice Return a Binary Tree in Level Order, then consider returning one sum per level instead of every value.
8. Coin change: why does a greedy choice fail?
For an unlimited supply of positive coin denominations, define dp[a] as the minimum number of coins needed to make amount a. Start with dp[0] = 0; unreachable amounts need a distinct sentinel. Consider only transitions from reachable smaller amounts.
With coins [1, 3, 4] and amount 6, taking the largest coin first gives 4 + 1 + 1, while the minimum is 3 + 3: two coins. Greedy selection is therefore not correct for arbitrary denominations.
The bottom-up approach costs O(Ad) time and O(A) space. This is pseudopolynomial: it depends on the numeric amount, not just the number of bits representing it. Very large targets may make the approach impractical.
Test amount 0, an unreachable target such as 7 with [2, 4], and invalid zero or negative denominations. The bounded-supply version needs a different state or update scheme. Try the free Blind 75 Coin Change exercise, then explain why its contract permits the recurrence.
9. Trapping rain water: which boundary fixes the current contribution?
With nonnegative bar heights and unit-width bars, water at an index is the smaller of the tallest left and right boundaries, minus the bar height. Prefix and suffix maxima give a straightforward O(n)-time, O(n)-space approach.
For [3, 0, 2, 0, 4], the contributions are [0, 3, 1, 3, 0], totaling 7. No bar can retain water without a sufficient boundary on both sides.
A two-pointer approach maintains running maxima from each side. Once the smaller running maximum determines a side, the opposite known boundary is already high enough; that side's contribution can be finalized before advancing inward. State this invariant instead of memorizing pointer movements. It gives O(n) time and O(1) auxiliary space.
Test [2, 0, 2] for 2 units, an empty input, a flat profile, and monotone heights for zero. Practice Optimize Trapping Rain Water and compare the clarity and storage costs of the two approaches.
10. Top K frequent values: how are ties resolved?
Count frequencies first, then choose among the m distinct values. A bounded heap keeps k candidates, with the worst retained candidate at its root. Expected counting plus selection takes O(n + m log(k + 1)) time and O(m + k) space. Producing a sorted result adds O(k log k) time.
Suppose the required output is frequency descending, then numeric value ascending. For [4, 4, 1, 1, 2], k = 2 produces [1, 4]; k = 1 produces [1]. A heap keyed only by (frequency, value) would evict the smaller tied value first, contradicting this rule. For integer values, a retention key (frequency, -value) puts the worse tied candidate first. Iterating the heap still does not produce ranked output.
A full sort costs O(n + m log m) expected time and may be simpler. Frequency buckets offer linear-time selection when the output contract permits arbitrary tie order; imposing an additional ordering can add work. Clarify k = 0 and k greater than m rather than silently choosing a policy.
Practice Find top-K frequent values with tiebreaks. An exact streaming frequency map still grows with the number of distinct values; a heap of size k does not make the whole algorithm constant-space.
Build a preparation loop you can repeat
For each pattern, write down the contract, the invariant, a small counterexample to a tempting wrong approach, and the time/space assumptions. Then solve a related prompt without notes and explain one change that would invalidate your original approach.
Use the 7-, 14-, or 30-day study-plan generator to distribute practice and review. If you are choosing a fixed problem list, compare Grind 75, Blind 75, and NeetCode 150 before adding more volume.
For broader hiring context, consult the Stack Overflow 2025 developer survey, CoderPad's 2026 State of Tech Hiring, SHL's report on hiring software developers, and HackerRank's Tech Recruiting Benchmark Report. These sources discuss developers, assessment, and hiring; they do not establish a ranking of these ten problems or predict what a particular employer will ask.
Comments (0)