O(1) constant space
easy 14 minO(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
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.
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 (2, 3, 10), the space is .
Pocket-sized memory
A million elements? Still just 2 or 3 variables. Nothing new is allocated per element.
Often in place
Many algorithms rearrange the input directly instead of making a copy.
The definition
Definitions
Input space vs auxiliary space
The input already takes cells, so if we counted it, every algorithm that reads an array would be 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
| Algorithm | Input space | Auxiliary space | Called |
|---|---|---|---|
| Find the max | 2 ints: i, best | ||
| Reverse in place | 3 ints: left, right, temp | ||
Reverse with arr[::-1] | a new list of | ||
| Recursive sum | stack frames | ||
| Pair sum with a hash set | up to stored values |
The picture
How memory grows with n
| Space class | n = 10 | n = 1,000 | n = 1,000,000 | Picture |
|---|---|---|---|---|
| 2 | 2 | 2 | two pointers L and R | |
| 10 | 1,000 | 1,000,000 | a copy, one cell per element | |
| 100 | 1,000,000 | an n by n grid |
Flat means flat
O(1) space
- Same few variables for any .
- 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 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 time, but space.
Pair sum with two pointers
left, right and s are ever stored. Moving a pointer rules out one value for good.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)) # NoneTechnique 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
Cost of an in-place reverse
In place: O(1) space
- Swap with two pointers and a temp.
- Three reverses rotate an array by .
- 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.
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]Running max or min
best = arr[0], update when beaten. 8 elements or 8 billion: one variable.Running sum or count
total += xkeeps 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: 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
Why they must meet
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
The call stack of a recursive sum
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 .
It often needs sorted input
Two pointers for pair sums only work on sorted data. Sorting first costs time.
It may be slower
A hash set gives pair sum in time on unsorted data with space. Two pointers need there.
Pair sum on unsorted data: pick your trade
| Approach | Time | Extra space | Input kept? |
|---|---|---|---|
| Check every pair | yes | ||
| Hash set of seen values | yes | ||
| Sort, then two pointers | with heap sort | no, reordered |
Catalogue
Common O(1) space algorithms
| Problem | Extra variables | Technique | Practice |
|---|---|---|---|
| Two sum on a sorted array | left, right | Two pointers | LC 167 |
| Reverse an array or string | left, right, temp | In-place swap | LC 344 |
| Sort colours (0, 1, 2) | low, mid, high | Dutch national flag | LC 75 |
| Container with most water | left, right, best | Two pointers | LC 11 |
| Move zeros to the end | write, read | Read and write pointers | LC 283 |
| Linked list cycle | slow, fast | Floyd's algorithm | LC 141 |
| Remove duplicates from sorted array | write, i | Read and write pointers | LC 26 |
| Rotate an array by k | k, two indexes | Three reverses | LC 189 |
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]Swapping with no temp at all
Pattern spotting
Recognising O(1) space
| Code shape | What it is | Space |
|---|---|---|
left, right = 0, n - 1 | Two pointers from both ends | |
while left < right: | Pointers converging | |
arr[i], arr[j] = arr[j], arr[i] | In-place swap | |
max_val = arr[0] | Running tracker | |
slow = slow.next; fast = fast.next.next | Floyd's algorithm | |
return f(arr, i + 1) | Recursion deep | , not constant |
arr[::-1], sorted(arr), [x for x in arr] | A new list | , not constant |
Phrases in a problem statement
| You read | It signals |
|---|---|
| "in place" or "constant extra space" | An explicit 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" elements | In-place rearrangement with read and write pointers |
Is this O(1) space?
Recap
Key takeaways
Key points
- O(1) space means the auxiliary memory is bounded by a constant: for every .
- Count auxiliary space, not the input. Finding the max uses 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 means space.
- Slices,
sorted(), comprehensions and string building quietly allocate . - The trade-off: in-place work destroys the input, and two pointers often need sorted data.