AlgoViz

O(1) constant time

easy 13 min

O(1) means an operation takes a fixed amount of work no matter how large the input is.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

ONE flip, ONE time: like a light switch, the room size does not matter.

A light switch. Flip it in a room with one bulb or a thousand and the flip takes the same moment. Array indexing, hash lookups and stack pushes work the same way: you go straight to the spot instead of searching for it.

Cheat sheet

Array index arr[i]
O(1)
Address formula
base + i × size
Hash map get, set, delete
O(1) average, O(n) worst
Stack push and pop
O(1)
list.append
O(1) amortised
len(list)
O(1), stored
deque append and popleft
O(1)
list.insert(0, x), pop(0)
O(n)
x in list
O(n); x in set is O(1)

Spot it when you see

  • You need fast lookups by key or ID: reach for a dict.
  • You keep asking have I seen this before: reach for a set.
  • Work only happens at one end: a stack or a deque.
  • A problem demands O(1) per operation, such as an LRU cache or a min stack.
  • A nested loop exists only to find something: replace the inner loop with a hash lookup.
  • You recompute the same value often: store it once and read it in O(1).

Tricks that stick

  • Light switch: one flip, any room size.
  • Mailbox: know the address, go straight there, skip the neighbours.
  • Piano key: press any note directly, no scanning from the lowest key.
  • Locker: know the number, open it, the rest stay shut.
  • Golden rule: if you can calculate exactly where it is, you can reach it in O(1).

Do not forget

  • Calling hash map lookups always O(1) and forgetting the collision worst case.
  • Using x in list inside a loop, which makes the loop O(n squared).
  • Using list.pop(0) or insert(0, x) as a queue instead of a deque.
  • Forgetting that one append can be O(n) during a resize.
  • Treating slices, max, min and string concatenation as constant time.
  • Reading O(1) as fast: it means the cost does not grow, not that it is small.