Most beginners read a coding problem, stare at it, and start typing, hoping a solution appears. When it doesn't, they look at the answer and feel they'll never be good at this. The problem usually isn't ability; it's not having a method.
This lesson gives you a six-step method that works for practice problems, coding tests and live interviews, then walks through a real problem with it from start to finish.
The six steps
- Understand the problem.
- Work through examples by hand, including tricky ones.
- Find a brute-force solution, however slow.
- Optimise it, using the patterns you know.
- Write the code, cleanly.
- Test it, and state its complexity.
It looks slow, but it's faster than coding the wrong thing and debugging it for an hour. Let's go through each step with one problem.
The problem. Given a list of daily prices of a share, find the maximum profit from buying on one day and selling on a later day. If no profit is possible, return 0.
Step 1: understand the problem
Restate it in your own words, and ask about anything unclear. In an interview, ask out loud; in a test, write your assumptions down.
- What's the input? A list of numbers, one per day.
- What's the output? One number: the best profit, or 0.
- Can I buy and sell on the same day? That gives 0 profit, so it doesn't matter.
- Must I sell after I buy? Yes. That's the key rule.
- How long can the list be? Say up to 100,000 days. That tells you how fast the solution must be: about 10⁵ items means O(n²), around 10¹⁰ steps, is too slow, and O(n) or O(n log n) is needed.
- Can the list be empty? Then the answer is 0.
Step 2: work through examples by hand
Write a few examples and solve them without code:
| Prices | Best trade | Profit |
|---|---|---|
[7, 1, 5, 3, 6, 4] | Buy at 1, sell at 6 | 5 |
[7, 6, 4, 3, 1] | Prices only fall | 0 |
[2, 4, 1] | Buy at 2, sell at 4 | 2 |
[5] | Only one day | 0 |
The third example is important: the lowest price (1) comes last, so you can't simply subtract the minimum from the maximum. Edge cases like this are where most bugs hide, so always include one empty or single-item case, one with duplicates, and one that breaks the obvious idea.
Step 3: find a brute-force solution
Don't try to be clever yet. What's the simplest thing that's definitely correct? Try every pair of buy day and later sell day:
def max_profit_brute(prices):
best = 0
for buy in range(len(prices)):
for sell in range(buy + 1, len(prices)):
best = max(best, prices[sell] - prices[buy])
return best
print(max_profit_brute([7, 1, 5, 3, 6, 4])) # 5
Two nested loops: O(n²) time, O(1) space. In an interview, say this out loud even if you don't write it: "The brute force is O(n²); let me see if I can do better." It shows you understand the problem and gives you a correct fallback.
Step 4: optimise
Ask: what work is being repeated? For each sell day, the brute force rescans all the earlier days to find the cheapest buy. But the cheapest earlier price can simply be remembered as we go.
So walk through the prices once. Keep the lowest price seen so far, and at each day, check the profit from selling today.
Questions that lead to faster solutions:
- Am I searching for something again and again? Store it in a variable, set or dictionary.
- Is the input sorted, or would sorting help? Think binary search or two pointers.
- Am I looking at a range of consecutive items? Think sliding window or prefix sums.
- Am I recomputing the same subproblem? Think memoisation, as in recursion explained.
Step 5: write the code
Now write it, with clear names:
def max_profit(prices):
lowest = float("inf")
best = 0
for price in prices:
lowest = min(lowest, price) # cheapest buy so far
best = max(best, price - lowest) # profit if we sell today
return best
In an interview, talk as you write: "I'm tracking the lowest price so far, and the best profit so far." Silence makes interviewers nervous; explaining shows your thinking even if you make a small slip.
Step 6: test it, and state the complexity
Run your examples from step 2, including the edge cases:
tests = [
([7, 1, 5, 3, 6, 4], 5),
([7, 6, 4, 3, 1], 0),
([2, 4, 1], 2),
([5], 0),
([], 0),
]
for prices, expected in tests:
assert max_profit(prices) == expected, prices
print("all tests pass")
all tests pass
Then trace one example by hand, line by line, the way an interviewer will. Finally, state the cost: O(n) time (one pass) and O(1) space (two variables). That's a big improvement from O(n²): for 100,000 days, about 100,000 steps instead of 5 billion.
What to do when you're stuck
- Solve a smaller version. What if the list had 2 items? 3?
- Draw it. Pointers, windows and trees become obvious on paper.
- Change one assumption. What if the input were sorted? What if you could use extra memory?
- Think about which pattern it resembles. Most problems are variations of ones you've seen. That's why keeping a notebook of patterns helps.
- Take a hint, not the solution. On practice sites, read only the first line of a hint or the problem's topic tag, then try again.
In a live interview
- Spend the first few minutes asking questions and writing examples. It isn't wasted time; interviewers score it.
- Say the brute force first, with its Big-O, then improve it.
- Ask "shall I code this approach?" before writing. It avoids coding something the interviewer doesn't want.
- If you can't find the optimal solution, a working brute force beats a broken clever one.
- When you finish, test without being asked.
Practice
Use the six steps on each problem. Write the brute force first, then improve it.
- Given a list of numbers, return the largest difference between two numbers in it, in any order.
Show the answer
The brute force checks every pair, O(n²). But the largest difference is always max − min, because order doesn't matter here (unlike the share problem):
def biggest_gap(nums):
return max(nums) - min(nums) if nums else 0
O(n) time. Step 1 matters: the rule about order changes the answer completely.
- Given a list, return the first number that appears twice, or None.
Show the answer
def first_repeat(nums):
seen = set()
for n in nums:
if n in seen:
return n
seen.add(n)
return None
print(first_repeat([3, 1, 4, 1, 5, 3])) # 1
Brute force compares every pair, O(n²). Remembering seen numbers in a set makes it O(n) time, O(n) space.
- Given a sorted list and a target, return True if two numbers add up to the target.
Show the answer
Brute force: every pair, O(n²). Because the list is sorted, use two pointers from both ends: if the sum is too small, move the left pointer right; if too big, move the right pointer left. O(n) time, O(1) space. See the two pointers technique.
Interview questions
What should you do first when given a coding problem in an interview?
Clarify it: restate the problem, ask about input size, edge cases and constraints, and work through an example. Then describe a brute-force approach and its complexity before optimising.
Why mention a brute-force solution if it's too slow?
It proves you understand the problem, gives a correct baseline to improve from and test against, and guarantees you have something working if time runs out.
How do input size limits hint at the expected complexity?
A rough guide: up to about 20 allows O(2ⁿ); about 500 allows O(n³); about 5,000 allows O(n²); 10⁵ to 10⁶ needs O(n log n) or O(n); larger needs O(log n) or O(1).
What to learn next
- Start on the most common data structure in arrays and Python lists for DSA.
- Use hash maps to turn O(n²) into O(n) in hash maps for coding problems.