What is the complexity of this code?
Four shapes turn linear code quadratic, and interviewers use all of them: in on a list inside a loop, += on a string in a loop, pop(0) used as a queue, and sorted() called inside a loop. Each is cheap once and fatal repeated.
Overview
The four shapes
1. x in a_list inside a loop. The membership test is O(n). Fix: build a set once, before the loop.
2. result += piece in a loop. Strings are immutable, so each step copies everything so far. Fix: collect into a list and "".join at the end.
3. list.pop(0) or insert(0, x). Both shift every other element. Fix: collections.deque.
4. sorted() inside a loop. Usually the data has not changed and the sort belongs outside it. Fix: sort once, or keep a heap if it really does change.
Step through it
What to watch
- Every individual line here is idiomatic and fine.
- The cost comes from the nesting, which is invisible on small input.
- Each fix is one line, and each is a different structure.
Say this out loud
"That's O(n²) - the membership test inside the loop is a linear scan. Build a set once before the loop and it's O(n)."