Skip to content

Lesson 4 of 40Foundations

How to Solve Problems

Follow a repeatable method for any coding problem, from first examples to a tested, optimised solution.

16 min read0/5 questions

Staring at a blank editor is the worst part of a coding interview. Strong candidates are not faster thinkers; they follow the same steps every time, so they always know what to do next. This lesson gives you that method and the pattern cheat sheet that the rest of the track fills in.

The method

Seven steps, in this order. The first two take longer than people expect, and that is fine.

  1. Understand. Restate the problem in your own words. Write two or three small examples by hand, including a weird one. Ask about input sizes, duplicates, negatives, empty input.
  2. Match a pattern. Look for trigger words ("sorted", "contiguous", "top k") and the input limits.
  3. Plan. Describe the approach in plain words or comments before writing code. Get agreement if someone is listening.
  4. Implement. Write clean code with good names. Small helper functions are fine.
  5. Test. Walk your examples through the code by hand, then the edge cases.
  6. Analyse. State the time and space complexity.
  7. Optimise. If it is too slow for the limits, find the bottleneck and improve that part.
Put it in order6 steps

Put the problem-solving method in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Brute force first, then improve

The brute force is the most obvious correct solution, usually trying every possibility. Say it out loud even if you know it is too slow. It proves you understand the problem, it gives you something to test against, and the improvement usually comes from asking "what work is it repeating?"

Worked example: given daily prices, find the best profit from buying on one day and selling on a later day (0 if you cannot profit).

Python
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 def max_profit(prices): cheapest = float("inf") best = 0 for p in prices: cheapest = min(cheapest, p) # best buy day so far best = max(best, p - cheapest) # sell today? return best for prices in [[7, 1, 5, 3, 6, 4], [7, 6, 4, 3, 1], []]: print(max_profit_brute(prices), max_profit(prices))
Output
Press Run (⌘ Enter) to see what happens.

The brute force is O(n²). The repeated work: for every sell day, it searches all earlier days for the cheapest price. But the cheapest earlier price is something you can remember as you go. Remembering it turns the inner loop into one variable, and the whole thing into O(n).

Recognising patterns from the wording

Problem statements leak hints. Learn these triggers and you will know where to start on most problems. Each pattern gets its own lesson in this track.

If the problem says...Reach for
"sorted array", "find a pair/target"binary search or two pointers
"contiguous subarray/substring", "longest/shortest with a rule"sliding window
"have we seen", "count", "duplicates", "anagram"hash map or set
"top k", "k largest/closest", "median of a stream"heap
"all combinations/permutations/subsets"backtracking
"shortest path" in an unweighted graph or gridBFS
"connected", "islands", "can reach"DFS or BFS
"number of ways", "min cost", "max value" with overlapping choicesdynamic programming
"intervals", "meetings", "overlapping ranges"sort by start, then sweep
"next greater/smaller", "warmer day", matching bracketsstack (monotonic stack)
"prefix", "autocomplete", "words starting with"trie
linked list "middle", "cycle", "kth from the end"fast and slow pointers
Match the pairs0/6 matched

Match each problem to the pattern its wording suggests.

Choose an item, then its match on the other side.
Match the pairs0/5 matched

One more round.

Choose an item, then its match on the other side.
Quick check
A problem gives n <= 20 and asks for the best way to split items into two groups. What does the small limit suggest?
Need a nudge? A hint rules out a wrong answer.

Talking aloud

In an interview, silence looks like being stuck even when you are not. Narrate in short sentences:

  • "Let me restate it: I get a list of prices and need the best buy-then-sell profit."
  • "Brute force is checking every pair, which is O(n²). n is up to 10⁵, so that is too slow."
  • "The repeated work is finding the cheapest earlier day, so I will track it as I go."
  • "Let me trace [7, 1, 5]: cheapest becomes 1, then profit 4."

If you are stuck, say what you are trying: "I am wondering whether sorting helps here, but sorting would lose the day order, which matters." That gives the interviewer a chance to nudge you.

Edge cases checklist

Run through this list before you say "done". Each item has broken real solutions.

Edge caseExample
Empty input[], ""
One element[5]
All the same[2, 2, 2]
Duplicates where the answer must be distinctsecond largest of [5, 5, 2]
Negatives and zero[-3, 0, -1]
Already sorted, reverse sorted[1, 2, 3], [3, 2, 1]
Very large valuesoverflow in other languages, float precision
No valid answerreturn -1, None, [] as the problem says
Quick check
This finds the largest number. Which input breaks it?
def largest(nums):
  best = 0
  for x in nums:
      if x > best:
          best = x
  return best
Need a nudge? A hint rules out a wrong answer.

Testing by hand

Before running anything, trace one example through your code with a small table of variables. This finds most bugs, and it is exactly what interviewers want to see.

Tracing max_profit on [7, 1, 5, 3, 6, 4]
7
0
↑p
1
1
5
2
3
3
6
4
4
5
cheapest = 7best = 0

Day 0: cheapest is 7. Selling today gives 0.

1/5

Then turn your examples into quick asserts so they run every time you change the code:

Python
def max_profit(prices): cheapest, best = float("inf"), 0 for p in prices: cheapest = min(cheapest, p) best = max(best, p - cheapest) return best assert max_profit([7, 1, 5, 3, 6, 4]) == 5assert max_profit([7, 6, 4, 3, 1]) == 0, "falling prices: no profit"assert max_profit([]) == 0, "empty input"assert max_profit([3]) == 0, "one day"print("all tests passed")
Output
Press Run (⌘ Enter) to see what happens.
ChallengeEasy

Second largest value

Return the second largest distinct value in nums. If there is no such value (fewer than two distinct numbers), return None in Python or null in TypeScript.

[3, 9, 4]      →  4
[5, 5, 2]      →  2
[7, 7]         →  None / null

This one is about edge cases. Do it in a single pass, without sorting.

def second_largest(nums: list[int]) -> int | None: pass
Key terms
brute force
The most direct correct solution, often trying every possibility. Say it first, then improve it.
pattern
A reusable approach (two pointers, sliding window, BFS...) triggered by recognisable wording in a problem.
edge case
An unusual input (empty, one item, all equal, negatives) that often breaks a solution.
trace
Walking an example through your code by hand, tracking each variable, to find bugs before running it.
bottleneck
The part of a solution that dominates its complexity, and so the part worth optimising.