O(1) constant time
easy 13 minO(1) means an operation takes a fixed amount of work no matter how large the input is.
See it run
Watch an array index, a hash map lookup and a stack push each finish in a fixed number of steps, then see the O(1) line stay flat while O(n) climbs.
Operations
Array index access
Read arr[5] from an array of 8 integers. The address is computed, not searched for: base + i × size.
Step 1 of 6
Problem: read arr[5] from 8 elements
- 100
- 201
- 302
- 403
- 504
- 605i
- 706
- 807
address (base 1000, 4 bytes each)
- 10000
- 10041
- 10082
- 10123
- 10164
- 10205
- 10246
- 10287
The array holds 10, 20, ..., 80 in one contiguous block of memory. It starts at address 1000 and every integer takes 4 bytes, so the cells sit at 1000, 1004, 1008 and so on. We want the value at index i = 5.
Step 1: Problem: read arr[5] from 8 elements
def get_element(arr, i, base=1000, size=4): if not 0 <= i < len(arr): # len() is stored, O(1) raise IndexError(i) addr = base + i * size # one multiply, one add return arr[i], addr # one memory readarr = [10, 20, 30, 40, 50, 60, 70, 80]print(get_element(arr, 5)) # (60, 1020)- Time
- O(1)
- Space
- O(1)
- arr[0] vs arr[999999]
- same cost
- find a value instead
- O(n) scan
Index access is O(1) because arrays are contiguous and every element has the same size. Lose either property (a linked list, variable-width records) and you lose the formula.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Membership tests on a list inside a loop
criticalx in some_listscans the list, O(n). Doing it n times makes the whole loop O(n²). A set or dict answers the same question in O(1) on average.Wrongseen = []for x in nums: if x in seen: # O(n) scan each time return True seen.append(x)Rightseen = set()for x in nums: if x in seen: # O(1) average return True seen.add(x)Using a list as a queue
majorlist.pop(0)andlist.insert(0, x)shift every remaining element one place, so each call is O(n). A deque supports O(1) work at both ends.Wrongqueue = [1, 2, 3]queue.insert(0, 0) # O(n) shiftfirst = queue.pop(0) # O(n) shiftRightfrom collections import dequequeue = deque([1, 2, 3])queue.appendleft(0) # O(1)first = queue.popleft() # O(1)Building a string with += in a loop
majorStrings are immutable, so each
+=may copy everything built so far. That is O(n) per step and O(n²) in total. Collect the pieces and join once.Wrongout = ""for word in words: out += word + " " # may copy out each timeRightparts = []for word in words: parts.append(word) # O(1) amortisedout = " ".join(parts) # one O(n) passTreating a slice as O(1)
majorarr[1:]copies n - 1 elements. Passing slices into recursion quietly turns an O(n) algorithm into O(n²). Pass an index instead.Wrongdef total(arr): if not arr: return 0 return arr[0] + total(arr[1:]) # copies each callRightdef total(arr, i=0): if i == len(arr): return 0 return arr[i] + total(arr, i + 1) # O(1) per callRecomputing the max or min every time
majormax(stack)scans the whole stack. If you need the minimum or maximum after every push and pop, store it alongside each element so reading it is O(1).Wrongstack.append(x)current_min = min(stack) # O(n) every pushRightlow = min(x, stack[-1][1]) if stack else xstack.append((x, low))current_min = stack[-1][1] # O(1)Calling hash map operations O(1) with no caveat
minorHash maps are O(1) on average. If many keys collide (a poor hash, or crafted inputs) a lookup degrades to O(n). Interviewers expect you to say so.
Wrong# "dict lookup is always O(1)"value = d[key]Right# O(1) average, O(n) worst case on collisionsvalue = d[key]
Interview tips
How to explain it
- O(1) means the work is bounded by a constant that does not depend on the input size n.
- The 1 is not one operation: 3 steps or 50 steps are both O(1) as long as the count never grows with n.
- Arrays compute an address, hash maps compute a bucket, stacks always know the top.
- Hash maps are O(1) average, O(n) worst case; list.append is O(1) amortised.
Spot it in code
- `arr[i]`, `arr[-1]`, `len(arr)`: index or stored size.
- `d[key]`, `key in d`, `s.add(x)`: hash map and set operations, average O(1).
- `stack.append(x)`, `stack.pop()`, `deque.popleft()`: work at an end.
- No loop over the input, and no call that hides one (in, min, max, slice, sort).
Memory tricks
- Light switch: one flip, whether the house has 1 bulb or 1,000.
- Mailbox: know the address, walk straight to it.
- Locker: know the number, open it. No checking the neighbours.
- Golden rule: if you can calculate exactly where it is, you can reach it in O(1).
Watch out
- `x in list`, `list.insert(0, x)`, `list.pop(0)`, slicing and string `+=` all look short but are O(n).
- A single append can be O(n) during a resize; only the average over many appends is O(1).
- Hashing a long string costs time proportional to its length; Python caches string hashes after the first time.