Solving problems in coding interviews
Knowing data structures is half the battle. Coding interviews test whether you can take an unfamiliar problem, choose an approach, explain it, code it correctly and analyse it, under time pressure and while talking. That's a skill you can practise. This final lesson gives you a method, a map of patterns, and a fully worked example.
A method for every problem
- Understand. Restate the problem. Ask about input sizes, edge cases (empty input, duplicates, negative numbers), and the expected output format. Work through a small example by hand.
- Brute force first. Describe the obvious solution and its complexity. It proves you understand the problem and gives you a fallback.
- Optimise. Look for the bottleneck: repeated work (cache it), searching (hash map, sorting, binary search), nested loops over contiguous ranges (two pointers, sliding window).
- Plan, then code. Talk through the approach before typing. Use clear names; write small helper functions.
- Test. Walk through your code with the example, then with edge cases. Fix bugs calmly.
- Analyse. State the time and space complexity, and mention trade-offs or further improvements.
Interviewers care as much about your communication as about the final code: think out loud, and treat it as solving the problem together.
Pattern map
| If the problem mentions… | Consider |
|---|---|
| Pairs/triples in a sorted array | Two pointers |
| Contiguous subarray or substring with a condition | Sliding window, prefix sums |
| "Have I seen this?", counting, grouping | Hash map / set |
| Sorted input, or "minimum value that works" | Binary search (on the answer) |
| Top k, k-th largest, merging sorted streams, scheduling | Heap |
| Matching brackets, "next greater", undo | Stack (monotonic stack) |
| Levels, nearest, shortest steps in a grid or unweighted graph | BFS |
| All combinations, permutations, subsets, puzzles | Backtracking |
| Hierarchies, recursion over children | Tree DFS |
| Dependencies, ordering | Topological sort |
| Connectivity as edges are added | Union-find |
| Weighted shortest paths | Dijkstra |
| Counting ways, min/max cost with overlapping choices | Dynamic programming |
| Prefix queries over many strings | Trie |
| Intervals (meetings, ranges) | Sort by start, then sweep (and maybe a heap) |
What the constraints tell you
The input size hints at the expected complexity, assuming roughly 10⁸ simple operations per second:
| n up to | Acceptable complexity |
|---|---|
| 10–12 | O(n!), O(2ⁿ·n) (permutations, subsets) |
| 20–25 | O(2ⁿ) |
| 500 | O(n³) |
| 5,000 | O(n²) |
| 10⁶ | O(n log n) or O(n) |
| 10⁹+ | O(log n) or O(1) (math, binary search) |
A worked example
Problem: Given a list of meeting time intervals, merge all overlapping intervals. Example:
[[1, 3], [8, 10], [2, 6], [15, 18], [17, 20]]→[[1, 6], [8, 10], [15, 20]]
Understand. Are intervals sorted? (Not necessarily.) Do touching intervals like [1, 4] and [4, 5] merge? (Let's say yes.) Can the list be empty? (Yes: return [].)
Brute force. Repeatedly scan every pair and merge any overlapping pair until nothing changes: O(n²) per pass, O(n³) overall. Too slow for large n.
Optimise. If the intervals were sorted by start, overlaps would always be with the most recent merged interval. Sorting costs O(n log n), then one pass merges.
Analyse. O(n log n) time for sorting, O(n) for the output. We copy each interval so the caller's input isn't modified, a detail worth mentioning.
A second example: the k most frequent words
Problem: Return the
kmost frequent words in a list, most frequent first; ties in alphabetical order.
Discussing alternatives earns credit: sorting all distinct words is O(m log m); a heap of size k is O(m log k); bucket sort by count is O(n).
Common mistakes to avoid
- Coding before understanding: ask questions first; most "hard" problems become easier with the right example.
- Ignoring edge cases: empty input, one element, duplicates, negative numbers, very large values.
- Off-by-one errors in loops and binary search: test with tiny inputs.
- Mutating inputs unexpectedly, or reusing a mutable default argument (
def f(x=[])). - Silent struggling: if you're stuck, say what you're thinking; interviewers often give hints.
- Not stating complexity: always finish with time and space, and why.
How to practise
- Solve problems by pattern, not randomly: do several sliding-window problems in a row until the pattern feels natural, then move on.
- Time yourself (around 30–40 minutes per problem), then study a good solution even when yours worked.
- Explain solutions out loud, or to a friend: communication is half the interview.
- Revisit problems a week later; re-solving from memory is what builds fluency.
- Curated lists (the "Blind 75", NeetCode 150) and sites like LeetCode, HackerRank and Codeforces provide plenty of practice.
- Prepare for system design interviews too (for mid-level roles and above): see the System Design track.
🎓 Data Structures & Algorithms track complete!
You've learned Big-O analysis, arrays and strings, hash maps and sets, two pointers and sliding windows, linked lists, stacks and queues, recursion and backtracking, sorting, binary search, trees and tries, heaps, graph traversal, dynamic programming, weighted shortest paths, topological sort and union-find, and a method for interviews.
Capstone challenge: a route-planning engine
Combine the track's ideas into one program:
- Load a graph of 20+ cities with distances (an adjacency list).
shortest_route(a, b)with Dijkstra, printing the path and total distance.fewest_stops(a, b)with BFS, and compare it with the shortest route.reachable_within(a, km): every city within a distance budget.- An autocomplete for city names using a trie.
cheapest_network(): the minimum spanning tree that connects every city.- Cache repeated route queries with an LRU cache you built yourself.
- Write tests for each function, including edge cases (unknown city, unreachable city, start = destination), and state every function's complexity.
1.What should you do first when given an interview problem?
2.The input can have up to 1,000,000 items. Which complexity is likely expected?
3.Why mention a brute-force solution before optimising?