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.

See it run

Watch two pointers, an in-place swap and a running maximum each finish with the same handful of variables, then see O(1) auxiliary space stay flat while a copy or a call stack grows with n.

Operations

Two-pointer pair sum

Find two numbers that add up to 16 in the sorted array [1, 3, 5, 7, 9, 11]. Two indexes and one running sum are all the extra memory, whatever the length.

Step 1 of 5

Problem: two numbers that sum to 16

  1. 10L
  2. 31
  3. 52
  4. 73
  5. 94
  6. 115R
left = 0right = 5target = 16extra memory = 2 ints

The array is sorted. Put L on the smallest value and R on the largest. These two indexes, plus one integer for their sum, are the only extra memory we will ever use.

Step 1: Problem: two numbers that sum to 16

def pair_sum(arr, target):    left, right = 0, len(arr) - 1      # 2 ints, for any n    while left < right:        s = arr[left] + arr[right]     # 1 more int, reused        if s == target:            return left, right        elif s < target:            left += 1                  # need a bigger sum        else:            right -= 1                 # need a smaller sum    return Noneprint(pair_sum([1, 3, 5, 7, 9, 11], 16))   # (2, 5): 5 + 11
Time
O(n)
Space
O(1)
hash set version
O(n) time, O(n) space
check every pair
O(n²) time, O(1) space

Two pointers on a sorted array replace a hash set: same O(n) time, but O(1) space instead of O(n). The price is that the input must already be sorted.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Recursion called O(1) space

    critical

    Every pending call keeps a stack frame. A recursion that goes n levels deep uses O(n) space even if it never creates a list, and Python raises RecursionError near 1,000 levels.

    Wrong
    def count(node):    if node is None:        return 0    return 1 + count(node.next)   # n frames deep
    Right
    def count(node):    total = 0    while node is not None:       # one variable, any length        total += 1        node = node.next    return total
  • Reversing with a slice when in place was required

    major

    arr[::-1] and reversed() into a list build a new list of n elements: O(n) auxiliary space. Swap with two pointers instead.

    Wrong
    def reverse(arr):    arr[:] = arr[::-1]        # builds an n-element copy first
    Right
    def reverse(arr):    l, r = 0, len(arr) - 1    while l < r:        arr[l], arr[r] = arr[r], arr[l]        l, r = l + 1, r - 1
  • Assuming sort() is O(1) space

    major

    Python's list.sort() is Timsort, which can use up to n/2 extra slots for merging. Sorting in place is not the same as O(1) auxiliary space. Heap sort is the classic O(1) space comparison sort.

    Wrong
    nums.sort()          # "sorts in place, so O(1) space"
    Right
    nums.sort()          # O(n) auxiliary space worst case (Timsort)# for true O(1) space use heap sort, or avoid sorting
  • Slicing inside a two-pointer loop

    major

    Checking s[l:r+1] == s[l:r+1][::-1] creates two new strings each time. Compare characters by index so nothing is copied.

    Wrong
    def is_pal(s):    return s == s[::-1]       # O(n) copy
    Right
    def is_pal(s):    l, r = 0, len(s) - 1    while l < r:        if s[l] != s[r]:            return False        l, r = l + 1, r - 1    return True
  • Using a hash set when the input is sorted

    minor

    On a sorted array, two pointers find a pair in O(n) time with O(1) space. A set gives the same time but stores up to n values.

    Wrong
    seen = set()for x in arr:    if target - x in seen:        return True    seen.add(x)               # O(n) space
    Right
    l, r = 0, len(arr) - 1while l < r:    s = arr[l] + arr[r]    if s == target:        return True    l, r = (l + 1, r) if s < target else (l, r - 1)
  • XOR swap on the same slot

    minor

    The XOR swap needs no temp, but if both names refer to the same memory cell the first XOR zeroes it. Guard against i == j, or just use a tuple swap.

    Wrong
    arr[i] ^= arr[j]arr[j] ^= arr[i]arr[i] ^= arr[j]          # i == j wipes the value to 0
    Right
    if i != j:    arr[i] ^= arr[j]    arr[j] ^= arr[i]    arr[i] ^= arr[j]

Interview tips

  • How to explain it

    • O(1) space means the extra memory is bounded by a constant that does not depend on n.
    • We usually mean auxiliary space: memory beyond the input itself (and beyond the output, if one is required).
    • Three ints or thirty ints is still O(1); what matters is that the count never grows with n.
    • Recursion depth counts: n nested calls means O(n) stack space.
  • Spot it in code

    • `left, right = 0, n - 1` with `while left < right`: two pointers.
    • `arr[i], arr[j] = arr[j], arr[i]`: swap in place.
    • `best = arr[0]` updated in a loop: a running tracker.
    • `slow = slow.next; fast = fast.next.next`: Floyd's cycle detection.
  • Memory tricks

    • Pocket rule: only use what fits in your pockets, never a backpack.
    • Two pointers: two index variables in your pockets.
    • Swap in place: one temp variable for the exchange.
    • Running max: one tracker variable.
  • Watch out

    • Slices, `sorted()`, list comprehensions and string building all allocate O(n).
    • In-place work destroys the input: ask whether the caller still needs it.
    • Two pointers for pair sums need sorted input; sorting first costs O(n log n) time.