How to Approach a Coding Interview Problem, Step by Step
An algorithm problem in an interview or a timed exercise tests two things at once: whether you can find a correct, efficient solution, and whether someone watching can follow how you got there. A fixed method helps with both. It keeps you from coding the wrong problem, gives you something useful to say at every stage, and turns "I am stuck" into a next step. This guide describes one such method. It is a way of working, not a guarantee of any result, and it works just as well for practice on your own.
Examples use Python 3.10 or later and only the standard library.
1. Restate and clarify
Say the problem back in your own words, then ask about everything the statement leaves open. Most wrong solutions are correct solutions to a slightly different problem. Questions worth asking almost every time:
- Input size. How large can n get? This one answer decides which complexity you are aiming for (step 4).
- Value ranges. Can numbers be negative, zero, very large? Are strings ASCII or arbitrary text?
- Duplicates. Can values repeat? Can the same element be used twice?
- Empty and tiny inputs. What should happen with an empty list, or a single item?
- Output. Return a value, an index, all solutions, or just whether one exists? Any one answer, or a specific one? Does order matter?
- Sorted or not. Is the input already in some order you can rely on?
2. Work two small examples by hand
Take the example from the statement and write the answer yourself, then make up a second one that is a little awkward: a duplicate, a negative number, no valid answer. Doing it by hand often shows you the algorithm, and the examples become your first tests. If you cannot solve a five-item example by hand, you are not ready to write code for it.
3. State a brute force and its complexity
Describe the most direct correct solution, even if it is slow, and say its time and space: "try every pair, O(n^2) time, O(1) extra space". This is not wasted effort. It proves you understand the problem, gives you a fallback if nothing better appears, and later serves as a reference to test the fast version against. Then ask whether it is fast enough for the input size you were given.
4. Use the input limits to pick a target
The size of n tells you roughly which complexity classes are realistic. A common rule of thumb is that a solution should do at most a few tens of millions of simple steps. Treat that as a rough guide, not a measurement: how much fits in a time limit depends on the language, the machine and the constant factors, and Python does much less per second than a compiled language. The step counts below come from the Big O Complexity Analyzer, which evaluates each class's representative function at n:
| n up to about | Class that usually fits | Count at that n |
|---|---|---|
| 20 | O(2^n), exhaustive search | 2^20 = 1,048,576 |
| 100 | O(n^3) | 100^3 = 1,000,000 |
| 10,000 | O(n^2), at the edge | 10,000^2 = 100,000,000 |
| 1,000,000 | O(n log n) or O(n) | n log2 n is about 20 million; n^2 would be 10^12 |
Read the table backward: if n can be a million, an O(n^2) idea is not worth coding, and you should look for O(n log n) or better before writing anything. If n is at most 20, an exponential search may be exactly what is wanted.
5. Look for a pattern
Most problems are variations on a short list of techniques. Ask which of these the problem's shape suggests:
- Sorting first, when order would make the rest easy (O(n log n)).
- Hashing, when you keep asking "have I seen this before?" (O(1) average per lookup; see hash tables).
- Two pointers or a sliding window, for pairs in sorted data or contiguous runs (O(n); see two pointers and sliding window).
- Binary search, on sorted data or on the answer itself when a condition is monotonic (O(log n) per search).
- BFS or DFS, when the input is a grid, network or set of dependencies (O(V + E)).
- Dynamic programming, when the brute force recomputes the same subproblems (states x work per state).
- Backtracking, when every solution is needed and n is small (exponential).
A useful question is: "what is the brute force doing over and over?" If it searches a list repeatedly, a set or a sort removes the repetition. If it recomputes overlapping subproblems, that is DP. If it rescans a window that moved by one, keep a running total instead.
6. Write the code with clear names
Say the plan in a sentence or two before you type, so a wrong idea is caught before it becomes code. Then write in small pieces with names that describe what they hold (seen, left, best_so_far), not a, b, tmp. A small helper function is fine if it makes the main loop readable. Talk as you go, briefly: what each part is for, not every keystroke.
7. Test out loud, then state the final complexity
Trace your code on the small examples from step 2, line by line, with actual values. Then try the edge cases from step 1: empty input, one element, all duplicates, negatives, no valid answer, the largest n. Finish by stating time and space for the final version and the assumption behind them ("O(n) average, because set lookups are O(1) on average").
A worked example
Problem: given a list of integers and a target, return whether any two different elements add up to the target.
- Clarify. Two different positions, but they may hold equal values. Numbers may be negative. An empty list or a single element has no pair. Return a boolean. Assume n can reach about a million.
- Examples. [2, 7, 11, 15] with target 9: yes (2 + 7). [5] with target 10: no, a single 5 cannot pair with itself. [5, 5] with target 10: yes.
- Brute force. Check every pair: O(n^2) time, O(1) space. At a million elements that is about 5 x 10^11 pairs, far too many.
- Target. The table says O(n log n) or O(n).
- Pattern. The brute force keeps asking "is target - x somewhere else in the list?", which is a membership question, so use a set. Walk the list once; for each x, check whether target - x was seen earlier, then add x. Checking before adding is what makes [5] return false and [5, 5] return true. (Sorting plus two pointers also works, in O(n log n).)
import random
def has_pair_brute(nums, target): # O(n^2) time, O(1) extra space
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return True
return False
def has_pair(nums, target): # O(n) average time, O(n) space
seen = set()
for x in nums:
if target - x in seen:
return True
seen.add(x)
return False
# edge cases said out loud, then checked
assert has_pair([], 5) is False
assert has_pair([5], 10) is False # one element cannot pair with itself
assert has_pair([5, 5], 10) is True # duplicates
assert has_pair([-3, 8], 5) is True # negatives
random.seed(1)
for _ in range(1000):
nums = [random.randint(-20, 20) for _ in range(random.randint(0, 8))]
target = random.randint(-30, 30)
assert has_pair(nums, target) == has_pair_brute(nums, target), (nums, target)
print("edge cases and 1000 random cases pass")
edge cases and 1000 random cases pass
The asserts are the spoken edge cases, written down. The random loop compares the fast version with the brute force on a thousand small inputs, with a fixed seed so any failure can be reproduced; it is the most dependable way to catch a fast version that is subtly wrong. Final answer: O(n) average time and O(n) extra space, against O(n^2) and O(1) for the brute force. The trade is memory for time, and it is worth saying so.
Checking your own estimate
The Interview Complexity Estimator is a rules table: you tick the techniques a solution uses and choose an input-size regime, and it reports the largest time and space class among them. It does not read or run your code, and its "difficulty" label is the site's own heuristic. Used that way, it is a quick cross-check of your reasoning. For the example above, "nested loops" in its large regime gives O(n²) time and O(1) space and the label "Hard", while "hash map / set lookups" plus "single pass" gives O(n) time and O(n) space and "Easy". Its regimes are labeled small (n up to about 100), medium (up to about 10^4) and large (beyond that).
When you are stuck
- Go back to the brute force and ask what it repeats.
- Solve a simpler version first: sorted input, no duplicates, a smaller limit.
- Work a larger example by hand and watch what you do; you are often running the algorithm already.
- Say what you are trying. A partial idea explained clearly is more useful to you and to a listener than silence.
Check yourself
- n is at most 15 and the problem asks for every valid arrangement. What class is acceptable? (Exponential: 2^15 = 32,768 subsets, so backtracking is reasonable.)
- Why check
target - x in seenbefore adding x? (So that an element is never paired with itself.) - Your solution is O(n^2) and n can be 10^6. What next? (Look for O(n log n) or O(n): sort, hash, or two pointers.)