How to Approach a Problem
A seven-step method for solving problems you have not seen before, a worked example, and what interviewers look for and ask at each step.
On this page
A problem-solving routine is a fixed sequence of steps that takes you from reading an unfamiliar problem to working, tested code. You restate the problem, solve a small case by hand, write a brute force, find what it wastes, choose a pattern that removes the waste, write the code, and test the edge cases. It prevents the two most common failures, which are solving a different problem from the one that was asked and stalling because no idea comes, and you use it on every problem that you cannot solve at first sight.
The seven steps
- Restate the problem. Say what the input is, what the output is, how large the input can be, and what should happen in odd cases such as empty input, no answer or ties.
- Solve a small example by hand. Pick 5 to 8 items and work out the answer yourself. What you do with your eyes and pencil is a first version of the algorithm.
- Write the brute force. This is the most obvious method that is certainly correct, even if it is slow. Work out its cost.
- Find the waste. Look for what the brute force computes more than once, and for what it checks although the check cannot change the answer.
- Pick a pattern that removes the waste. The table later on this page maps common problem signals to patterns.
- Write the code for the improved method.
- Test the edge cases. Try empty input, one item, all items equal, and the answer at each end of the input.
The seven steps on a worked problem
Your phone counts your steps each day, and your goal is 8,000 steps. Find your longest streak, which is the largest number of days in a row on which you reached the goal.
Step 1: restate it
The input is a list steps with one whole number per day in date order, and a number goal. The output is the length of the longest run of neighbouring days where steps[i] >= goal. Before coding, decide the odd cases: a day with exactly 8,000 steps counts, and both an empty list and a list with no qualifying day give 0. Assume the list can hold up to 100,000 days.
Step 2: solve a small example by hand
Take one week with the counts 8,200, 9,100, 4,000, 8,500, 10,200, 9,000 and 2,500. Marking each day as met or missed gives ✓ ✓ ✗ ✓ ✓ ✓ ✗. The runs of ticks have lengths 2 and 3, so the answer is 3. You did this with a single scan, counting ticks and starting again from zero at every cross.
Step 3: write the brute force
Treat every day as a possible start of a streak, walk forward from it for as long as the goal is met, and keep the longest walk.
function longestStreakSlow(steps, goal) {
let best = 0;
for (let start = 0; start < steps.length; start++) {
let length = 0;
while (start + length < steps.length && steps[start + length] >= goal) {
length++;
}
best = Math.max(best, length);
}
return best;
}def longest_streak_slow(steps, goal):
best = 0
for start in range(len(steps)):
length = 0
while start + length < len(steps) and steps[start + length] >= goal:
length += 1
best = max(best, length)
return bestWrite this version even if you can already see a faster one, because it gives you something to test the faster version against. Its cost is the problem: if every day meets the goal, the walks add up to about n²/2 checks, which is 5 billion for 100,000 days. That is too slow.
Step 4: find the waste
There are two kinds of waste here. A walk that starts in the middle of a streak can never beat the walk that started at the beginning of that streak. And every walk re-checks days that an earlier walk already checked, only to stop at the same place again.
A useful question for finding this kind of waste is "what do I know about today, given what I knew about yesterday?" If today meets the goal, the streak that ends today is yesterday's streak plus 1, and otherwise it is 0. One number carried from day to day replaces all the separate walks.
Step 5: pick a pattern
The pattern is a single pass that carries running values, like the "best so far" in What Is an Algorithm. Here you carry two values, the length of the streak ending today and the best length seen so far. It is also the simplest case of a sliding window.
Step 6: write the code
best = 0, current = 0for each day d: if d >= goal: current = current + 1 else: current = 0 best = max(best, current)return best- steps082001910024000385004102005900062500
- goal
- 8000
- current
- 0
- best
- 0
1Before any day is read, both the current streak and the best streak are 0.
- steps08200d1910024000385004102005900062500
- goal
- 8000
- current
- 1
- best
- 1
28,200 reaches the goal, so the current streak is 1 and the best is 1.
- steps0820019100d24000385004102005900062500
- goal
- 8000
- current
- 2
- best
- 2
39,100 reaches the goal, so the streak is yesterday's streak plus 1. The current streak is 2 and the best is 2.
- steps082001910024000d385004102005900062500
- goal
- 8000
- current
- 0
- best
- 2
44,000 misses the goal, so the current streak drops to 0. The best stays at 2.
- steps08200191002400038500d4102005900062500
- goal
- 8000
- current
- 1
- best
- 2
58,500 reaches the goal, so a new streak starts at 1.
- steps08200191002400038500410200d5900062500
- goal
- 8000
- current
- 2
- best
- 2
610,200 reaches the goal, so the current streak is 2, which ties the best.
- steps0820019100240003850041020059000d62500
- goal
- 8000
- current
- 3
- best
- 3
79,000 reaches the goal, so the current streak is 3, which is a new best.
- steps082001910024000385004102005900062500d
- goal
- 8000
- current
- 0
- best
- 3
82,500 misses the goal, so the current streak resets to 0. The best stays at 3.
- steps082001910024000385004102005900062500
- answer
- 3
- checks
- 7
- brute force
- 16
9The answer is 3, found with 7 checks. The brute force needed 16 checks on the same week.
function longestStreak(steps, goal) {
let best = 0;
let current = 0; // length of the streak that ends today
for (const day of steps) {
current = day >= goal ? current + 1 : 0;
best = Math.max(best, current); // update every day
}
return best;
}
longestStreak([8200, 9100, 4000, 8500, 10200, 9000, 2500], 8000); // 3def longest_streak(steps, goal):
best = 0
current = 0 # length of the streak that ends today
for day in steps:
current = current + 1 if day >= goal else 0
best = max(best, current) # update every day
return best
longest_streak([8200, 9100, 4000, 8500, 10200, 9000, 2500], 8000) # 3| Approach | Time | Space | Why |
|---|---|---|---|
| Walk from every start | O(n²) | O(1) | Up to n + (n − 1) + ... + 1 checks. |
| One pass | O(n) | O(1) | One check per day, and two numbers are kept. |
Step 7: test the edge cases
Run each of these through the one-pass code.
- An empty list
[]never enters the loop, so the result is 0. - The list
[3000, 5000]has no qualifying day, so the result is 0. - The list
[8000]shows that exactly the goal counts, so the result is 1. - The list
[9000, 9000, 9000]has every day qualifying, so the result is 3. - The list
[2000, 9000, 9000]has its best streak at the very end, so the result is 2. Solutions that update the best value only when a streak ends fail on this input.
Matching problem signals to patterns
The pattern in step 5 comes from what the problem statement asks for. The table below lists the most common signals and the pattern each one usually points to. Treat it as a first guess to check against your small example, because a keyword can mislead you. The word "longest", for example, suggests a sliding window, but a window only works when you can decide from the items alone whether to grow or shrink it, and that is not true of every longest-stretch problem.
| If the problem… | Try |
|---|---|
| asks "have I seen this before", needs a partner value, or counts things | Hash map or set |
| asks about pairs in a sorted array | Two pointers |
| wants the longest or shortest stretch of neighbouring items | Sliding window |
| asks many range-sum questions | Prefix sums |
| has sorted data, or wants the smallest value that works | Binary search, or binary search on the answer |
| needs the next bigger item, or matching brackets | Stack, or monotonic stack |
| has nested data or a tree | Recursion, or tree traversals |
| wants the fewest moves in a grid or network | Breadth-first search |
| wants the cheapest route when links have costs | Dijkstra |
| has tasks that must come before others | Topological sort |
| merges groups, or asks whether two items are connected | Union-find |
| wants every combination or ordering | Backtracking |
| wants the k largest items, or repeatedly takes the smallest | Heap |
| has overlapping time ranges | Intervals |
| counts ways, or builds a best total from smaller choices | Dynamic programming |
| seems solved by always taking the best-looking option | Greedy, after you have proved it works |
| searches words by their beginning | Trie |
What to do when a step does not work
You cannot see a brute force
This happens with problems that ask for the best of many choices, such as the best way to split a list or to pick items. The brute force is then to try every choice with a recursive function that makes one choice and calls itself for the rest, and to keep the best result. That is backtracking. It is usually exponential, but it is correct, and the repeated sub-problems it computes are exactly the waste that dynamic programming removes.
Your small example suggests nothing
If solving the example by hand does not reveal a method, the example is probably too easy or too special. Choose one with a tie, a repeated value or a case where the obvious choice is wrong. You can also solve an easier version first, for example with the input already sorted or with a smaller limit, and then ask what changes in the real version.
Using the input size limits to choose a target complexity
The input limits tell you how much work per item you can afford. A computer does a few hundred million simple steps per second, so the maximum input size roughly fixes the slowest acceptable complexity. If the limits are small, the brute force may already be good enough: with n up to 500, an O(n²) solution takes 250,000 steps and finishes instantly, so there is nothing to optimise.
| n up to about | Affordable cost |
|---|---|
| 10 | O(n!), which tries every order |
| 20 | O(2ⁿ), which tries every subset |
| a few thousand | O(n²), which tries every pair |
| 1,000,000 | O(n log n) |
| 100,000,000 | O(n), with only simple work per item |
| more than that | O(log n) or O(1), because you cannot even read every item |
Two mistakes that cost the most
In the interview
An interviewer watching you solve a new problem is judging the process as much as the answer. Each step of the routine corresponds to something they want to see, and most interviewers are happy to answer questions at the start.
What they look for at each step
In step 1 they look for clarifying questions: input size, whether values can be negative or repeated, what to return when there is no answer. In steps 2 and 3 they want you to say the brute force and its cost out loud before improving it, because it shows you have a correct solution to fall back on. In step 5 they want a reason for the pattern you chose, based on something in the problem statement such as a sorted input, a contiguous stretch or a limit on the size. In steps 6 and 7 they expect you to walk through your own code on an example and to name edge cases without being asked.
Follow-up questions
"Can you do better than that?" This usually means the interviewer expects an improvement over the brute force. Go back to step 4 and say what the current solution repeats or checks needlessly, then say which data structure or pattern removes it. For the streak problem the answer is that each walk re-checks days that an earlier walk already covered, so one pass with a running count replaces them.
"What is the time and space complexity?" Give both, with the reason. For the one-pass solution the time is O(n) because each day is examined once, and the space is O(1) because only two numbers are kept.
"What if the data arrives as a stream and you cannot store it?" The one-pass solution already works, because it never looks back at earlier days and only needs the current streak and the best streak.
"What would you test?" Name the edge cases from step 7 and explain why each could break the code: empty input, no qualifying item, exactly the threshold, everything qualifying, and a result that ends at the last element.
When you are stuck
Say so, and keep talking. Write the brute force and state its cost, because a correct slow solution is worth more than silence and often shows the waste on its own. Then walk through your small example and point at the step that repeats work. If you are still stuck, ask whether the interviewer wants you to optimise further or whether a hint about the data structure is available. Interviewers usually expect to give one hint, and how you use it is part of what they judge.
Check yourself
You have read a new problem once. What should you do first?
The limits say a list can hold up to 100,000 numbers, and your brute force is O(n²). What does that tell you?
With a goal of 8,000, what does the one-pass longestStreak return for [9000, 7000, 8000, 8100]?
What to practise next
The next lesson, Arrays, starts the data structures that the patterns in the table are built on, and each pattern then has its own lesson. Apply the seven steps to every problem you practise until they become a habit.