O(1) constant time
easy 13 minO(1) means an operation takes a fixed amount of work no matter how large the input is.
Video lesson · Chapter 1 of 5
A cabinet with a predictable address
O(1) constant time
1:26Reel
Read caption
Luma relights one pixel using a zero-based array index and a fixed element size. One address, one jump.
How it works
Step through the idea, or press Play.
Compute where it is. An index, a hash or a stored top pointer tells you the exact location without looking anywhere else
Understand it
Start here
What O(1) means
An operation is O(1), or constant time, when the work it does is bounded by a fixed number that does not depend on the input size . Reading arr[0] and reading arr[999999999] take the same time. The data can grow a millionfold and the cost stays put.
No n in the count
Three steps, fifty steps, a thousand steps: all if the count never grows with the input.
Compute, do not search
Constant time comes from knowing exactly where the answer lives, so nothing is scanned.
The gold standard
It is the cheapest growth rate there is. Picking the right data structure often turns into .
The definition
The picture
A flat line while n grows
| Input size | operations | operations |
|---|---|---|
| 100 | 1 | 100 |
| 10,000 | 1 | 10,000 |
| 1,000,000 | 1 | 1,000,000 |
| 1 billion | 1 | 1,000,000,000 |
Doubling the input changes nothing
Example 1
Array index access
An array stores its elements in one contiguous block of memory, and every element has the same size . So the address of element is a single calculation from the block's starting address. No element before needs to be visited.
The address formula
arr[3] lives at address 1012 whatever the array's length.Memory layout of [0, 10, 20, 30, 40]
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 0 | 10 | 20 | 30 | 40 |
| Address | 1000 | 1004 | 1008 | 1012 | 1016 |
arr[3] = 30 is found by computing 1012, not by walking past cells 0, 1 and 2.def address(base, i, size): return base + i * size # O(1): no looparr = [10, 20, 30, 40, 50, 60, 70, 80]for i in [0, 5, 7]: print(f"arr[{i}] = {arr[i]} at address {address(1000, i, 4)}")# arr[0] = 10 at address 1000# arr[5] = 60 at address 1020# arr[7] = 80 at address 1028arr[i].Example 2
Hash map lookup
How a dict finds a key
Key to bucket
table = [[] for _ in range(6)] # 6 bucketsdef put(key, value): bucket = table[hash(key) % len(table)] for pair in bucket: if pair[0] == key: pair[1] = value return bucket.append([key, value])def get(key): for k, v in table[hash(key) % len(table)]: if k == key: return v raise KeyError(key)for k, v in [("apple", 5), ("banana", 3), ("cherry", 7), ("date", 2)]: put(k, v)print(get("banana")) # 3dict and set work on the same idea, with open addressing instead of lists.Deep dive
Why the average stays constant
With keys in buckets, the load factor is the average number of keys per bucket. A lookup costs one hash plus a scan of one bucket.
Expected lookup cost with chaining
Average case or worst case?
| Operation | Average | Worst case |
|---|---|---|
d[key], key in d | ||
d[key] = v | amortised | |
del d[key] | ||
s.add(x), x in s |
Example 3
Stack push and pop
- 1push(40)write at top + 1
- 2top += 1move the pointer
- 3pop()read the top
- 4top -= 1move it back
Two steps each way. Elements below the top are never moved, read or counted.
stack = [10, 20, 30] # 30 is on topstack.append(40) # push: O(1) amortisedprint(stack) # [10, 20, 30, 40]print(stack.pop()) # 40, O(1)print(stack.pop()) # 30, O(1)print(stack, stack[-1]) # [10, 20] 20 (peek is an index: O(1))O(1): work at the end
append(x)andpop()on a list.appendleftandpoplefton adeque.- Insert or delete at a linked list's head.
O(n): work at the front of a list
insert(0, x)shifts all elements right.pop(0)shifts all elements left.- Inserting in the middle shifts everything after it.
Deep dive
Amortised O(1): the occasional resize
A Python list lives in a fixed-size block. When the block is full, the next append allocates a bigger block and copies every element: that one append is . Because the capacity grows by a constant factor, those copies are rare enough to average out.
Total cost of n appends with doubling
What one append does
Everyday
O(1) in real life
Light switch
One flip and the light is on. The size of the room, or the number of bulbs, does not change how long the flip takes.
Mailbox
Know the address and you walk straight to it. You never check the neighbours' boxes first.
Piano key
Press any key directly. You do not scan from the lowest C up to the note you want.
Locker
Know the number, open the locker. The other lockers stay shut.
Can you reach it in O(1)?
len(arr) is the last kind: the length is stored, not counted.Catalogue
Common O(1) operations
| Operation | Python | Cost |
|---|---|---|
| Array access by index | arr[i], arr[-1] | |
| Length | len(arr) | , stored |
| Stack push and pop | append(x), pop() | amortised / |
| Queue enqueue and dequeue | deque.append, deque.popleft | |
| Linked list head insert or delete | node.next = head; head = node | |
| Delete a node given a pointer (doubly linked) | relink prev and next | |
| Variable assignment and swap | a, b = b, a | |
| Arithmetic on fixed-size numbers | + - * / % | |
| Hash map get, set, delete | d[k], d[k] = v, del d[k] | average |
| Hash set add, contains, remove | s.add(x), x in s | average |
Common mistakes
Looks constant, is not
| Operation | Why it is not O(1) | Cost |
|---|---|---|
| Finding the max or min of unsorted data | Every element must be checked | |
| Searching an unsorted array | Linear scan required | |
| Insert or delete in the middle of an array | Elements after it must shift | |
String += in a loop | Builds a new string each time | per concat |
| Array slice or copy | Copies the elements | for elements |
x in some_list | Linear search through the list | |
list.insert(0, x), list.pop(0) | Every element shifts | |
| Accessing the -th node of a linked list | Must walk links |
A hidden loop inside a loop
Truly O(1)
len(arr): the length is stored.d.get(k): hash, then one bucket.stack[-1]: peek is an index.
Short to write, still O(n)
max(arr): scans everything.arr[1:]: copies items.arr.index(x): searches from the left.
Interviews
Where O(1) wins interviews
| Problem | Brute force | With an O(1) structure |
|---|---|---|
| Two Sum | check every pair | : hash map of value to index |
| Contains Duplicate | or sort in | : set membership |
| Valid Parentheses | repeatedly delete pairs, | : stack push and pop |
| First Unique Character | count each character | : hash map of counts |
| LRU Cache | list scan per access | get and put: hash map + doubly linked list |
| Min Stack | min() per query | push, pop and get_min |
def two_sum(nums, target): seen = {} # value -> index for i, x in enumerate(nums): if target - x in seen: # O(1) average return [seen[target - x], i] seen[x] = i # O(1) average return []print(two_sum([2, 7, 11, 15], 9)) # [0, 1]print(two_sum([3, 2, 4], 6)) # [1, 2]in check and each insert is O(1) on average, so the loop is O(n).Recap
Key takeaways
Key points
- O(1) means the cost is capped by a constant that does not depend on ; the 1 is not one operation.
- Arrays are O(1) to index because .
- Hash maps compute a bucket with : O(1) on average, O(n) if every key collides.
- Stacks push and pop at the top in O(1);
list.appendis O(1) amortised because resizes are rare. x in list,insert(0, x),pop(0), slicing,maxand string+=look short but are O(n).- Golden rule: if you can calculate exactly where it is, you can reach it in O(1).