How to Solve a New Problem

A method you can repeat

  1. Understand – restate the problem; work the example by hand.
  2. Brute force first – the simplest (even slow) idea, and its Big-O.
  3. Look for clues – sorted input? “shortest”? “all possible”? See the table.
  4. Improve – pick a better pattern or data structure; check the Big-O against the limits.
  5. Code it in small pieces. Watch for overflow (long long).
  6. Test – the example, then edge cases: n = 1, all equal, biggest values.

Think of it like this: Like a doctor: listen to the symptoms, recognise the pattern, apply the treatment that works for it.

Clue → technique → STL tool

ClueTechniqueC++ tools
sorted data, find a pair / positiontwo pointers, binary searchlower_bound, upper_bound
stretch of neighbours, longest/shortestsliding windowdeque, counting arrays
many range-sum questionsprefix sumsvector<long long>
seen before? counting? pairs adding to Xhashingunordered_map, unordered_set
sorted order, next bigger valuebalanced BSTset, map
next bigger / previous smallermonotonic stackstack
k largest, always the best nextheappriority_queue
fewest steps in a maze/networkBFSqueue
groups, islands, explore allDFS / union-findrecursion, a DSU struct
weighted shortest pathDijkstrapriority_queue with greater
tasks with prerequisitestopological sortin-degree + queue
all combinations / arrangementsbacktrackingnext_permutation
how many ways / best total with overlapping choicesdynamic programmingvector tables

Big-O from the limits

A computer does roughly 10⁸ simple C++ operations per second:

n up toYou can afford
10–20O(2ⁿ), O(n!)
500O(n³)
5,000O(n²)
10⁶O(n log n) or O(n)
10¹⁸O(log n) or O(1)
HOME LABS COMMUNITY DASHBOARD