How to Solve a New Problem

A method you can repeat

  1. Understand – say the problem in your own words. Work through the example by hand.
  2. Brute force first – what's the simplest (even slow) way? Write down its Big-O.
  3. Look for clues – sorted input? “shortest”? “all possible”? Use the table below.
  4. Improve – pick a better pattern or data structure. Check the new Big-O.
  5. Code it in small pieces.
  6. Test – the example, then edge cases: empty input, one item, all items the same, very big numbers.

Think of it like this: Like a doctor: listen to the symptoms (the problem), recognise the pattern (“this looks like the flu”), then apply the treatment you know works for that pattern.

Clue → technique cheat sheet

If the problem says or has...Try
sorted list, “find a pair”two pointers, binary search
“stretch of neighbouring items”, longest/shortest windowsliding window
many “sum from i to j” questionsprefix sums
“have I seen this before?”, counting, pairs that add to Xdict / set (hashing)
“next bigger / previous smaller”monotonic stack
brackets, undo, most recent firststack
“k largest / smallest”, always the best nextheap
fewest steps in a maze or networkBFS
connected groups, islands, explore everythingDFS / union-find
shortest path with distancesDijkstra
tasks with prerequisitestopological sort
“all combinations / arrangements”backtracking
“how many ways”, “best total”, choices that overlapdynamic programming
“best choice now never hurts later”greedy

Big-O from the input size

The limits in a problem quietly tell you how fast your solution must be (a computer does roughly 10⁷–10⁸ simple steps per second):

If n is up to...You can afford about
10–20O(2ⁿ), O(n!) – backtracking
500O(n³)
5,000O(n²)
1,000,000O(n log n) or O(n)
10¹⁸O(log n) or O(1) – maths or binary search
HOME LABS COMMUNITY DASHBOARD