Foundations: measuring code · Lesson 5 of 23
How to approach any interview problem
A repeatable process from understanding to code to testing, and how to talk while solving.
Most people stumble in interviews not from lack of knowledge but by coding immediately. The interviewer wants to see how you think. Use the same steps every time:
Understand and ask
Examples and edge cases
Brute force
Optimise
Write the code
Test by hand
1. Understand: restate the problem. Ask: can numbers be negative? Duplicates? Empty input? What's the largest size? (Size hints the target: n = 10⁵ means O(n) or O(n log n).) 2. Examples: one normal case and edge cases (empty, one item, all equal). 3. Brute force: state the simple solution and its complexity, even if slow. Now you have something. 4. Optimise: where is work repeated? A hash map? Sorting? Two pointers? 5. Write while talking. 6. Test with your examples, line by line.
| If you see… | Think of… |
|---|---|
A sorted array | Binary search or two pointers |
"Longest/shortest contiguous part" | Sliding window |
"Seen this before?" / counting | Hash map / Set |
Brackets, "next greater" | Stack |
Shortest path, levels | BFS |
All combinations | Backtracking |
"Number of ways" / "max value" with choices | Dynamic programming |
"Top/smallest k" | Heap |
You'll see this table come to life through the rest of the track.
Quick question
The problem says n up to 10⁵. Which complexity will usually pass within a second?
Spot the bug
This returns the largest number, but an edge case breaks it. Which line?
Exercise
Fix largest so it works with negative numbers. It must print -2 9.
Expected output: -2 9
function largest(nums) {
let best = 0
for (const x of nums) {
if (x > best) best = x
}
return best
}
console.log(largest([-5, -2, -9]), largest([3, 9, 1]))Practise on real problems
Practice problems that use what you learned here. Solve them in JavaScript, Python or C++.
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.