O(1) constant space
easy 14 minO(1) space means an algorithm uses a fixed amount of extra memory, a few variables, no matter how large the input is.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
The pocket rule: only use what fits in your pockets, never a backpack.
Counting people walking through a gate. You do not write down every name; you keep one clicker in your pocket and press it. A thousand people or a million, the clicker is the same size. That clicker is O(1) space.
Cheat sheet
- Two pointers
- 2 indexes, O(1)
- Swap in place
- 1 temp, O(1)
- Running max or sum
- 1 tracker, O(1)
- Dutch national flag
- 3 pointers, O(1)
- Floyd's cycle detection
- slow and fast, O(1)
- XOR swap
- 0 extra variables
- Slice or copy
- O(n)
- Recursion n deep
- O(n) stack
- Python list.sort
- O(n) worst case
Spot it when you see
- The problem says in place or constant extra space.
- The problem says modify the input array.
- A sorted array and find a pair or triplet.
- The problem says without using extra space.
- Move or partition elements within the array.
- A linked list with a possible cycle, or find its middle.
Tricks that stick
- Pocket rule: pointers and counters fit in a pocket; copies need a backpack.
- Two pointers: two index variables in your pocket.
- Swap in place: one temp variable for the exchange.
- Running max: one tracker variable, overwritten, never a history.
- Double n and ask: did memory move? If not, it is O(1).
Do not forget
- Calling a recursive solution O(1) space and forgetting the call stack.
- Hiding a copy in a slice, sorted, a comprehension or string building.
- Assuming list.sort is O(1) space because it sorts in place.
- Destroying the input when the caller still needs it.
- Using two pointers for a pair sum on unsorted data.
- XOR swapping a cell with itself and zeroing it.