MohitDecodes
Back to blogsDSA

How to Analyze Time & Space Complexity Without Guessing

November 16, 2026 · 6 min read

In coding interviews, jumping straight into code without checking constraints is the fastest way to write an O(n²) solution that times out on `n = 10^5`. Learning to estimate complexity takes two minutes and saves you from coding the wrong approach.

Read constraints as a complexity hint

  • n <= 20: exponential O(2^n) or backtracking O(n!) is usually expected.
  • n <= 1,000: O(n²) nested loops will pass comfortably.
  • n <= 100,000: you need O(n log n) (sorting, binary search, heap) or O(n) (hash map, two pointers, sliding window).

Don't forget hidden costs inside loops

A single `for` loop isn't automatically O(n). Calling `arr.shift()`, `arr.splice()`, string concatenation in a tight loop, or sorting inside a loop changes the total work significantly. Always multiply loop iterations by the cost of the operations inside the loop.

// Looks like O(n), actually O(n^2) because shift() re-indexes the array
while (queue.length > 0) {
  const item = queue.shift();
  process(item);
}

And for recursion, ask two questions: how many recursive calls are on the stack at maximum depth (space complexity), and how many total nodes are in the recursion tree (time complexity)?

Further reading