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.

Video lesson · Chapter 1 of 5

A cabinet with a predictable address

0:00 / 4:35

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.

Step 1 of 3

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 nn. 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 O(1)O(1) 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 O(n)O(n) into O(1)O(1).

The definition

T(n)=O(1)  ⟺  ∃ c>0:  T(n)≤c   for all nT(n) = O(1) \iff \exists\, c > 0 : \; T(n) \le c \;\text{ for all } n
There is one constant cc that caps the cost for every input size. The cost may vary a little from call to call, but it never grows past cc.

The picture

A flat line while n grows

Input size nnO(1)O(1) operationsO(n)O(n) operations
1001100
10,000110,000
1,000,00011,000,000
1 billion11,000,000,000
The O(1)O(1) column never changes. That is the whole point: the data structure you choose decides which column you live in.

Doubling the input changes nothing

T(2n)=T(n)=ccompare O(n):  T(2n)=2 T(n)T(2n) = T(n) = c \qquad\text{compare } O(n):\; T(2n) = 2\,T(n)
Linear work doubles when the input doubles. Constant work does not notice.

Example 1

Array index access

An array stores its elements in one contiguous block of memory, and every element has the same size ss. So the address of element ii is a single calculation from the block's starting address. No element before ii needs to be visited.

The address formula

addr(i)=base+i⋅s1000+3⋅4=1012\text{addr}(i) = \text{base} + i \cdot s \qquad 1000 + 3 \cdot 4 = 1012
One multiply and one add, then one memory read. With base 1000 and 4-byte integers, arr[3] lives at address 1012 whatever the array's length.

Memory layout of [0, 10, 20, 30, 40]

Index01234
Value010203040
Address10001004100810121016
arr[3] = 30 is found by computing 1012, not by walking past cells 0, 1 and 2.
Python
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 1028
The address calculation spelled out. Python does the same thing for you inside every arr[i].
Edit and run it in your browser

Example 2

Hash map lookup

How a dict finds a key

Hashing and indexing are constant time. The only loop is inside one bucket, and a healthy table keeps buckets very short.

Key to bucket

i=h(k) mod mi = h(k) \bmod m
hh turns the key into an integer and  mod m\bmod m folds it into the mm buckets. After that the lookup is just the array access from Example 1.
Python
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"))                         # 3
A tiny hash table with chaining. dict and set work on the same idea, with open addressing instead of lists.
Edit and run it in your browser

Deep dive

Why the average stays constant

With nn keys in mm buckets, the load factor α=n/m\alpha = n / m is the average number of keys per bucket. A lookup costs one hash plus a scan of one bucket.

Expected lookup cost with chaining

E[cost]=O(1+α),α=nm≤αmax⁡  ⇒  O(1)E[\text{cost}] = O(1 + \alpha), \qquad \alpha = \frac{n}{m} \le \alpha_{\max} \;\Rightarrow\; O(1)
Tables grow (and rehash) when α\alpha passes a limit, roughly two thirds in CPython's dict and 0.75 in Java's HashMap. Keeping α\alpha bounded keeps the expected cost constant.

Average case or worst case?

Both conditions hold for Python's dict and set, Java's HashMap and C++'s unordered_map in normal use.
OperationAverageWorst case
d[key], key in dO(1)O(1)O(n)O(n)
d[key] = vO(1)O(1) amortisedO(n)O(n)
del d[key]O(1)O(1)O(n)O(n)
s.add(x), x in sO(1)O(1)O(n)O(n)
Insertions are amortised because an insert that triggers a resize rehashes every key once.

Example 3

Stack push and pop

Every stack operation touches only the top
  1. 1push(40)write at top + 1
  2. 2top += 1move the pointer
  3. 3pop()read the top
  4. 4top -= 1move it back

Two steps each way. Elements below the top are never moved, read or counted.

Python
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))
Push 40 onto [10, 20, 30], then pop twice.
Edit and run it in your browser

O(1): work at the end

  • append(x) and pop() on a list.
  • appendleft and popleft on a deque.
  • Insert or delete at a linked list's head.

O(n): work at the front of a list

  • insert(0, x) shifts all nn elements right.
  • pop(0) shifts all nn 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 O(n)O(n). Because the capacity grows by a constant factor, those copies are rare enough to average out.

Total cost of n appends with doubling

n⏟writes+1+2+4+⋯+n2⏟copies<n+n=2n  ⇒  2nn=O(1) per append\underbrace{n}_{\text{writes}} + \underbrace{1 + 2 + 4 + \dots + \tfrac{n}{2}}_{\text{copies}} < n + n = 2n \;\Rightarrow\; \frac{2n}{n} = O(1) \text{ per append}
Amortised O(1)O(1) is a guarantee about a sequence: nn appends cost O(n)O(n) in total, even though a single append can cost O(n)O(n). CPython grows by about 12.5% rather than doubling, and the argument works for any constant factor.

What one append does

The expensive branch runs only when the size hits the capacity, which happens about log⁡n\log n times over nn appends.

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)?

Every O(1) operation answers one of these questions with yes. len(arr) is the last kind: the length is stored, not counted.

Catalogue

Common O(1) operations

OperationPythonCost
Array access by indexarr[i], arr[-1]O(1)O(1)
Lengthlen(arr)O(1)O(1), stored
Stack push and popappend(x), pop()O(1)O(1) amortised / O(1)O(1)
Queue enqueue and dequeuedeque.append, deque.popleftO(1)O(1)
Linked list head insert or deletenode.next = head; head = nodeO(1)O(1)
Delete a node given a pointer (doubly linked)relink prev and nextO(1)O(1)
Variable assignment and swapa, b = b, aO(1)O(1)
Arithmetic on fixed-size numbers+ - * / %O(1)O(1)
Hash map get, set, deleted[k], d[k] = v, del d[k]O(1)O(1) average
Hash set add, contains, removes.add(x), x in sO(1)O(1) average
Python integers grow without limit, so arithmetic on huge numbers costs time proportional to their digit count. For everyday sizes treat it as O(1)O(1).

Common mistakes

Looks constant, is not

OperationWhy it is not O(1)Cost
Finding the max or min of unsorted dataEvery element must be checkedO(n)O(n)
Searching an unsorted arrayLinear scan requiredO(n)O(n)
Insert or delete in the middle of an arrayElements after it must shiftO(n)O(n)
String += in a loopBuilds a new string each timeO(n)O(n) per concat
Array slice or copyCopies the elementsO(k)O(k) for kk elements
x in some_listLinear search through the listO(n)O(n)
list.insert(0, x), list.pop(0)Every element shiftsO(n)O(n)
Accessing the kk-th node of a linked listMust walk kk linksO(k)O(k)

A hidden loop inside a loop

∑j=1nO(j)⏟x in list=O(n2)∑j=1nO(1)⏟x in set=O(n)\sum_{j=1}^{n} \underbrace{O(j)}_{x \text{ in list}} = O(n^2) \qquad \sum_{j=1}^{n} \underbrace{O(1)}_{x \text{ in set}} = O(n)
Swapping a list for a set inside a loop removes a whole factor of nn. This one change fixes many slow interview solutions.

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 n−1n - 1 items.
  • arr.index(x): searches from the left.

Interviews

Where O(1) wins interviews

ProblemBrute forceWith an O(1) structure
Two SumO(n2)O(n^2) check every pairO(n)O(n): hash map of value to index
Contains DuplicateO(n2)O(n^2) or sort in O(nlog⁡n)O(n \log n)O(n)O(n): set membership
Valid Parenthesesrepeatedly delete pairs, O(n2)O(n^2)O(n)O(n): stack push and pop
First Unique CharacterO(n2)O(n^2) count each characterO(n)O(n): hash map of counts
LRU CacheO(n)O(n) list scan per accessO(1)O(1) get and put: hash map + doubly linked list
Min StackO(n)O(n) min() per queryO(1)O(1) push, pop and get_min
The pattern: do nn constant-time operations instead of nn linear ones.
Python
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]
Two Sum in one pass. Each in check and each insert is O(1) on average, so the loop is O(n).
Edit and run it in your browser

Recap

Key takeaways

Key points

  • O(1) means the cost is capped by a constant that does not depend on nn; the 1 is not one operation.
  • Arrays are O(1) to index because addr(i)=base+i⋅s\text{addr}(i) = \text{base} + i \cdot s.
  • Hash maps compute a bucket with h(k) mod mh(k) \bmod m: O(1) on average, O(n) if every key collides.
  • Stacks push and pop at the top in O(1); list.append is O(1) amortised because resizes are rare.
  • x in list, insert(0, x), pop(0), slicing, max and string += look short but are O(n).
  • Golden rule: if you can calculate exactly where it is, you can reach it in O(1).

Sources