AlgoViz

O(1) constant space

easy 14 min

O(1) space means an algorithm uses a fixed amount of extra memory, a few variables, no matter how large the input is.

Video lesson · Chapter 1 of 6

A whole row and two spare clips

0:00 / 5:27

O(1) constant space

1:26Reel

Read caption

A pinball score scan overwrites its current best and needs constant extra space. One scoreboard, any number of scores.

How it works

Step through the idea, or press Play.

Step 1 of 3

Keep a few variables. Pointers, a temp slot, a running max or sum: a fixed set that never grows with n

Understand it

Start here

What O(1) space means

An algorithm uses O(1) space when the extra memory it needs stays the same however large the input gets. Whether it processes 10 elements or 10 billion, it keeps the same few variables: two indexes, a temp slot, a running maximum. Memory does not scale with the input.

  • Fixed set of variables

    Count the extra variables. If the count can be written without nn (2, 3, 10), the space is O(1)O(1).

  • Pocket-sized memory

    A million elements? Still just 2 or 3 variables. Nothing new is allocated per element.

  • Often in place

    Many O(1)O(1) algorithms rearrange the input directly instead of making a copy.

The definition

S(n)=O(1)  ⟺  ∃ c:  Saux(n)≤c   for all nS(n) = O(1) \iff \exists\, c:\; S_{\text{aux}}(n) \le c \;\text{ for all } n
Saux(n)S_{\text{aux}}(n) is the auxiliary space: memory used beyond the input. It must stay below one fixed constant cc for every input size.

Definitions

Input space vs auxiliary space

The input already takes nn cells, so if we counted it, every algorithm that reads an array would be O(n)O(n) space and the label would say nothing. That is why space complexity normally means auxiliary space: the extra memory the algorithm creates on top of the input.

Splitting total memory

Stotal(n)=Sinput(n)⏟n cells, given+Saux(n)⏟what we allocateS_{\text{total}}(n) = \underbrace{S_{\text{input}}(n)}_{n \text{ cells, given}} + \underbrace{S_{\text{aux}}(n)}_{\text{what we allocate}}
Finding the max of an array has Stotal=n+2S_{\text{total}} = n + 2 but Saux=2S_{\text{aux}} = 2, so we call it O(1)O(1) space.
AlgorithmInput spaceAuxiliary spaceCalled
Find the maxnn2 ints: i, bestO(1)O(1)
Reverse in placenn3 ints: left, right, tempO(1)O(1)
Reverse with arr[::-1]nna new list of nnO(n)O(n)
Recursive sumnnnn stack framesO(n)O(n)
Pair sum with a hash setnnup to nn stored valuesO(n)O(n)
Same input in every row. Only the auxiliary column decides the class.

The picture

How memory grows with n

Space classn = 10n = 1,000n = 1,000,000Picture
O(1)O(1)222two pointers L and R
O(n)O(n)101,0001,000,000a copy, one cell per element
O(n2)O(n^2)1001,000,000101210^{12}an n by n grid
An n×nn \times n table at n=100n = 100 already needs 10,000 cells. The O(1)O(1) row never changes.

Flat means flat

S(2n)S(n)=1   for O(1)S(2n)S(n)=2   for O(n)S(2n)S(n)=4   for O(n2)\frac{S(2n)}{S(n)} = 1 \;\text{ for } O(1) \qquad \frac{S(2n)}{S(n)} = 2 \;\text{ for } O(n) \qquad \frac{S(2n)}{S(n)} = 4 \;\text{ for } O(n^2)
Double the input and see what happens to memory. Constant space does not move at all.

O(1) space

  • Same few variables for any nn.
  • Works on huge inputs and memory-tight devices.
  • Usually means working in place.

O(n) space

  • Memory grows with every element.
  • A copy, a hash set, a stack of nn calls.
  • Can run out of memory on large inputs.

Technique 1

Two pointers

Put one index at each end of a sorted array and move them toward each other. Each comparison tells you which pointer to move, so the pair is found in one pass with just two index variables. This replaces a hash set: same O(n)O(n) time, but O(1)O(1) space.

Pair sum with two pointers

Only left, right and s are ever stored. Moving a pointer rules out one value for good.
Python
def pair_sum(arr, target):    left, right = 0, len(arr) - 1      # 2 ints, for any n    while left < right:        s = arr[left] + arr[right]        if s == target:            return left, right        elif s < target:            left += 1                  # bigger sum needed        else:            right -= 1                 # smaller sum needed    return Noneprint(pair_sum([1, 3, 5, 7, 9, 11], 16))   # (2, 5): 5 + 11 = 16print(pair_sum([1, 3, 5, 7, 9, 11], 100))  # None
Find 16 in [1, 3, 5, 7, 9, 11]: 1 + 11 = 12, 3 + 11 = 14, 5 + 11 = 16. Three checks, three integers of memory.
Edit and run it in your browser

Technique 2

In-place modification

Instead of writing results into a new array, rearrange the input itself. Reversing swaps the two ends and moves inward; each swap needs one temp slot. Rotating, partitioning and removing duplicates all work the same way.

Reversing in place

[1, 2, 3, 4, 5] becomes [5, 2, 3, 4, 1], then [5, 4, 3, 2, 1]. Two swaps, one reused temp.

Cost of an in-place reverse

swaps=⌊n2⌋⇒T(n)=O(n),Saux(n)=3=O(1)\text{swaps} = \left\lfloor \frac{n}{2} \right\rfloor \Rightarrow T(n) = O(n), \qquad S_{\text{aux}}(n) = 3 = O(1)
5 elements need 2 swaps; the middle element stays put. Time is linear, space is constant.

In place: O(1) space

  • Swap with two pointers and a temp.
  • Three reverses rotate an array by kk.
  • Input is overwritten.

Copying: O(n) space

  • arr[::-1] builds a new list.
  • arr[-k:] + arr[:-k] builds two slices and a third list.
  • Input is preserved.

Technique 3

Running trackers

When you only need a summary of what you have seen, keep the summary and drop the history. One variable tracks the maximum, the minimum, the sum or the count of any array. Kadane's maximum subarray keeps just two: the best sum ending here and the best overall.

Python
def find_max(arr):    best = arr[0]                 # 1 tracker    for x in arr:        if x > best:            best = x    return bestdef max_subarray(arr):            # Kadane: 2 trackers    here = best = arr[0]    for i in range(1, len(arr)):  # index loop: no slice copy        here = max(arr[i], here + arr[i])   # best sum ending at i        best = max(best, here)    return bestprint(find_max([3, 7, 2, 9, 1, 8, 4, 6]))          # 9print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5]))  # 6: [4, -1, 2, 1]
Each function keeps a fixed number of variables while it scans.
Edit and run it in your browser
  • Running max or min

    best = arr[0], update when beaten. 8 elements or 8 billion: one variable.

  • Running sum or count

    total += x keeps one number; the values themselves are never stored.

  • Kadane

    Two numbers capture everything needed about every subarray seen so far.

Technique 4

Fast and slow pointers

To detect a cycle in a linked list you could store every visited node in a set: O(n)O(n) space. Floyd's tortoise and hare uses two pointers instead. The slow one moves 1 step, the fast one 2. If there is a cycle the fast pointer laps the slow one and they meet; if not, the fast one reaches the end.

Floyd's cycle detection

Two node references, whatever the list's length. The same trick finds the middle node and solves the happy number problem.

Why they must meet

gapt+1=gapt−1(modλ)\text{gap}_{t+1} = \text{gap}_t - 1 \pmod{\lambda}
Inside a cycle of length λ\lambda, each round the fast pointer closes the gap by exactly one node, so the gap reaches 0 within λ\lambda rounds. Time O(n)O(n), space O(1)O(1).

The trap

Why recursion breaks O(1)

A recursive function can look memory-free: no lists, no dicts. But every call that has not returned yet keeps a stack frame with its arguments, locals and return address. The deepest chain of pending calls is memory, and it counts.

Space of a recursion

Saux(n)=d(n)⏟max depth×c⏟frame sizesum(i)→sum(i+1):  d(n)=n+1⇒O(n)S_{\text{aux}}(n) = \underbrace{d(n)}_{\text{max depth}} \times \underbrace{c}_{\text{frame size}} \qquad \text{sum}(i) \to \text{sum}(i+1): \; d(n) = n + 1 \Rightarrow O(n)
Recursive binary search has depth about log⁡2n\log_2 n, so it uses O(log⁡n)O(\log n) space. Only a loop, or a language that eliminates tail calls, gets back to O(1)O(1). Python does not eliminate tail calls.

The call stack of a recursive sum

Every level is still on the stack when the base case runs. Python stops at about 1,000 levels with RecursionError.

Trade-offs

What O(1) space costs you

  • It may destroy the input

    In-place work overwrites the original. If the caller still needs it, you must copy first, and the copy is O(n)O(n).

  • It often needs sorted input

    Two pointers for pair sums only work on sorted data. Sorting first costs O(nlog⁡n)O(n \log n) time.

  • It may be slower

    A hash set gives pair sum in O(n)O(n) time on unsorted data with O(n)O(n) space. Two pointers need O(nlog⁡n)O(n \log n) there.

Pair sum on unsorted data: pick your trade

ApproachTimeExtra spaceInput kept?
Check every pairO(n2)O(n^2)O(1)O(1)yes
Hash set of seen valuesO(n)O(n)O(n)O(n)yes
Sort, then two pointersO(nlog⁡n)O(n \log n)O(1)O(1) with heap sortno, reordered
No row wins on every column. Interviewers want you to name the trade, not just the answer.

Catalogue

Common O(1) space algorithms

ProblemExtra variablesTechniquePractice
Two sum on a sorted arrayleft, rightTwo pointersLC 167
Reverse an array or stringleft, right, tempIn-place swapLC 344
Sort colours (0, 1, 2)low, mid, highDutch national flagLC 75
Container with most waterleft, right, bestTwo pointersLC 11
Move zeros to the endwrite, readRead and write pointersLC 283
Linked list cycleslow, fastFloyd's algorithmLC 141
Remove duplicates from sorted arraywrite, iRead and write pointersLC 26
Rotate an array by kk, two indexesThree reversesLC 189
Every row uses two or three variables, never anything sized by nn.
Python
def reverse(arr, i, j):    while i < j:        arr[i], arr[j] = arr[j], arr[i]        i, j = i + 1, j - 1def rotate_right(arr, k):    n = len(arr)    if n == 0:        return arr    k %= n    reverse(arr, 0, n - 1)       # [7, 6, 5, 4, 3, 2, 1]    reverse(arr, 0, k - 1)       # [5, 6, 7, 4, 3, 2, 1]    reverse(arr, k, n - 1)       # [5, 6, 7, 1, 2, 3, 4]    return arrprint(rotate_right([1, 2, 3, 4, 5, 6, 7], 3))  # [5, 6, 7, 1, 2, 3, 4]
Rotate right by k with three in-place reverses: reverse all, then the first k, then the rest.
Edit and run it in your browser

Swapping with no temp at all

a←a⊕b,b←a⊕b=a0,a←a⊕b=b0a \leftarrow a \oplus b,\quad b \leftarrow a \oplus b = a_0,\quad a \leftarrow a \oplus b = b_0
XOR swap exchanges two integers with zero extra variables, because x⊕x=0x \oplus x = 0. It fails if aa and bb are the same memory cell, and a tuple swap is clearer in practice.

Pattern spotting

Recognising O(1) space

Code shapeWhat it isSpace
left, right = 0, n - 1Two pointers from both endsO(1)O(1)
while left < right:Pointers convergingO(1)O(1)
arr[i], arr[j] = arr[j], arr[i]In-place swapO(1)O(1)
max_val = arr[0]Running trackerO(1)O(1)
slow = slow.next; fast = fast.next.nextFloyd's algorithmO(1)O(1)
return f(arr, i + 1)Recursion nn deepO(n)O(n), not constant
arr[::-1], sorted(arr), [x for x in arr]A new listO(n)O(n), not constant

Phrases in a problem statement

You readIt signals
"in place" or "constant extra space"An explicit O(1)O(1) space requirement
"modify the input array"In-place modification is allowed
"sorted array" plus "find a pair or triplet"Two pointers
"without using extra space"No hash maps, no copies
"move" or "partition" elementsIn-place rearrangement with read and write pointers

Is this O(1) space?

Check allocations, then hidden copies, then recursion depth. Only a clean pass through all three is constant space.

Recap

Key takeaways

Key points

  • O(1) space means the auxiliary memory is bounded by a constant: Saux(n)≤cS_{\text{aux}}(n) \le c for every nn.
  • Count auxiliary space, not the input. Finding the max uses n+2n + 2 cells in total but only 2 extra.
  • The four tools: two pointers, in-place swaps, running trackers, fast and slow pointers.
  • Recursion costs one stack frame per pending call: depth nn means O(n)O(n) space.
  • Slices, sorted(), comprehensions and string building quietly allocate O(n)O(n).
  • The trade-off: in-place work destroys the input, and two pointers often need sorted data.

Sources