← Data structures and algorithms for coding interviews

Lesson 1 of 6

How to think about complexity and approach any problem

2 min read

Big-O in one page

Big-O describes how time or memory grows as the input size n grows, ignoring constants.

ComplexityNameTypical examplen = 10⁵ feasible?
O(1)constanthash map lookupyes
O(log n)logarithmicbinary searchyes
O(n)linearone pass over an arrayyes
O(n log n)linearithmicsortingyes
O(n²)quadraticnested loops over the arrayborderline (10¹⁰ is too slow)
O(2ⁿ)exponentialall subsetsonly for n ≈ 20

Rule of thumb: about 10⁸ simple operations per second. Read the constraints first: n ≤ 10⁵ means you need O(n log n) or better; n ≤ 20 invites backtracking.

Space complexity counts extra memory: a hash set of all elements is O(n); recursion uses O(depth) stack space.

The interview process that works

  1. Clarify: input size, ranges, negatives, duplicates, empty input, sorted or not, what to return.
  2. Examples: walk through one normal and one edge case by hand.
  3. Brute force: state it and its complexity. It shows you can solve it at all.
  4. Optimise: which pattern removes the repeated work? (hashing, sorting, two pointers, prefix sums, a heap, DP).
  5. Code cleanly, with good names, talking as you go.
  6. Test: dry-run your examples and edge cases; fix bugs calmly.
  7. Analyse the final time and space complexity.

Interviewers grade communication and process, not just the final answer. Silence is the most common reason good coders fail.

Recognising patterns from the wording

Clue in the problemTry
"pairs/triplets", sorted arraytwo pointers
"contiguous subarray/substring", "longest/shortest window"sliding window
"have we seen this before?", counts, duplicateshash map / set
"sorted", "minimum value that works"binary search (also on the answer)
"next greater", matching bracketsstack
"k largest/smallest", "merge k"heap
tree or graph, "levels", "shortest path in steps"BFS
"all combinations/permutations"backtracking
"number of ways", "min/max cost", overlapping choicesdynamic programming

Sign up free to save your progress.

How to think about complexity and approach any problem · Data structures and algorithms for coding interviews · HireSol