AdvancedHabits & complexity

Why some “nested loops” are still O(n)

Count total work, not loop nesting. If each element enters and a or window once, the whole thing is .

The idea

A while loop inside a for loop looks like , but what matters is how many times the inner loop runs in total. In a or , each element is added once and removed at most once: 2n operations overall.

Dynamic arrays use the same idea: occasional O(n) resizes average out to per append.

Worked example

Daily Temperatures with a stack

  1. The inner while pops indices.
  2. Each index is pushed once and popped at most once.
  3. So across the whole run there are at most n pops: O(n) total, even though one step can pop many.

How to spot it

  • that only move forward, monotonic stacks and , , dynamic arrays.

Common mistakes

  • Calling these O(n²) in an interview: explain the total-work argument instead.
  • Assuming every inner loop is : if the inner can move backwards, it isn't.

Practise it

Go further