A method for coding rounds
Most failed coding rounds fail in the first five minutes or the last five: starting to type before understanding the problem, or stopping without testing. This six-step routine fixes both.
The six steps
- Restate. Say the problem back in one or two sentences.
- Example. Write one small input and its expected output by hand, and confirm it with the interviewer.
- Simple first. Describe the most obvious correct approach and its cost, even if it is slow.
- Improve. Say what would make it faster or use less memory, and agree which version to write.
- Write. Small functions, clear names, talking as you go.
- Test. Trace your example through the code line by line, then try an empty input and a malformed one.
What to know before you practise
- Dictionaries and sets: counting, grouping, and checking membership quickly.
- Sorting with a key, and when sorting is the whole answer.
- Splitting and parsing lines of text; converting strings to numbers safely.
- Queues and stacks, and a heap for "the largest k" questions.
- Reading a file line by line instead of loading it all into memory.
- Rough cost: one pass is O(n), a sort is O(n log n), a loop inside a loop is O(n²).
A worked opening
Problem: "Given web server log lines, return the five paths with the most requests." A strong first two minutes sounds like this.
Said aloud"So I get lines of text, each with a path in it, and I return the five most frequent paths with their counts. Can I assume the path is always the third field? What should happen to a line that is missing fields: skip it and count it? How big is the input: does it fit in memory? The simple approach is a dictionary from path to count in one pass, then sort by count and take five. That is O(n) to count and O(p log p) to sort p distinct paths. If p is very large I could keep a heap of five instead. I will write the dictionary version first."
from collections import Counter
def top_paths(lines, k=5):
counts = Counter()
skipped = 0
for line in lines:
parts = line.split()
if len(parts) < 3: # malformed: skip, but keep count
skipped += 1
continue
counts[parts[2]] += 1
return counts.most_common(k), skipped
Try the linked exercise · 10 minOn-call coverage gaps
Start problemEdge cases to name every time
- Empty input, and input with a single item.
- Malformed or partial lines.
- Duplicates and ties: what order should equal items come back in?
- Very large input: does it still fit in memory?
- Boundaries: the first and last item, a value exactly on a limit.
Common mistakes
- Typing before agreeing on an example.
- Silence while thinking. Say "give me thirty seconds to think" and then narrate.
- Optimising before anything works.
- Saying "done" without running a single input through the code.
- Hiding a bug you noticed. Pointing it out and fixing it scores higher than never making it.