AlgoViz

O(n) linear space

easy 14 min

O(n) space means the extra memory an algorithm needs grows in proportion to its input: double n and the memory doubles.

See it run

Watch a hash map, a copied list, a memo table and a call stack each grow one slot per element, then see how memory scales with n.

Operations

Two Sum with a hash map

Find two numbers in [2, 7, 11, 15, 3, 8] that add up to 11. A hash map of values seen so far turns each partner check into one lookup, at the cost of up to n stored entries.

Step 1 of 9

Set up: an empty map

  1. 20
  2. 71
  3. 112
  4. 153
  5. 34
  6. 85

seen (hash map): value → index

  1. ·0
  2. ·1
  3. ·2
  4. ·3
  5. ·4
  6. ·5
i = -need = -entries = 0extra memory = 0 of n = 6 slots

We want indices of two numbers that sum to 11. For each number we ask one question: *have I already seen its partner?* The answer lives in seen, a dictionary from value to index. It starts empty, so the extra memory is 0, but it can grow to one entry per element: S(n) = O(n).

Step 1: Set up: an empty map

def two_sum(nums, target):    seen = {}                       # value -> index: up to n entries, O(n) space    for i, num in enumerate(nums):        need = target - num        if need in seen:            # O(1) average lookup            return seen[need], i        seen[num] = i               # one more entry per element    return Noneprint(two_sum([2, 7, 11, 15, 3, 8], 11))   # (4, 5)
Time
O(n)
Space
O(n)
brute force
O(n²) time, O(1) space
this input
15 pairs vs 6 lookups

When a hash map makes something fast, say the price out loud: "O(n) time, but O(n) extra space for the map."

Common mistakes

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

  • Forgetting the recursion stack

    critical

    Every pending call keeps a frame in memory. A recursive function that goes n levels deep uses O(n) space even if it never builds a list. In Python it also hits the recursion limit near 1,000.

    Wrong
    def total(nums, i=0):    if i == len(nums):        return 0    return nums[i] + total(nums, i + 1)   # "O(1) space"? No: n frames
    Right
    def total(nums):    s = 0    for x in nums:      # one int: truly O(1) extra space        s += x    return s
  • Slicing inside a loop or recursion

    major

    arr[1:] copies n - 1 elements. Doing it once is O(n) space; doing it on every recursive call keeps n copies alive at once and costs O(n²) memory and time. Pass an index instead.

    Wrong
    def has(arr, x):    if not arr:        return False    return arr[0] == x or has(arr[1:], x)   # a new copy per call
    Right
    def has(arr, x, i=0):    if i == len(arr):        return False    return arr[i] == x or has(arr, x, i + 1)  # no copies
  • Building a string with += in a loop

    major

    Strings are immutable, so each += may create a new string. The final string is O(n) either way, but repeated concatenation can copy O(n²) characters in total. Collect pieces in a list and join once.

    Wrong
    out = ""for word in words:    out += word + " "      # may copy the whole string each time
    Right
    parts = []for word in words:    parts.append(word)out = " ".join(parts)      # one O(n) build
  • Reaching for 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 hash set gives the same time but spends O(n) memory for nothing.

    Wrong
    def pair_sum_sorted(nums, target):    seen = set()                       # O(n) space, not needed    for x in nums:        if target - x in seen:            return True        seen.add(x)    return False
    Right
    def pair_sum_sorted(nums, target):    l, r = 0, len(nums) - 1            # O(1) space    while l < r:        s = nums[l] + nums[r]        if s == target:            return True        if s < target:            l += 1        else:            r -= 1    return False
  • Calling a frequency map always O(n)

    minor

    A counter holds one entry per distinct key, so it is O(k) for k distinct values. For lowercase letters k is at most 26, which is O(1). Say which bound applies.

    Wrong
    counts = Counter(s)   # "always O(n) space"
    Right
    counts = Counter(s)   # O(k) distinct keys:# O(1) for a fixed alphabet, O(n) if all distinct

Interview tips

  • How to explain it

    • O(n) space means extra memory grows in proportion to the input: double n, double the memory.
    • Count auxiliary space only: the input itself is usually not included.
    • Typical sources: a hash map or set, a result list, a memo table, a visited set, a queue or stack, and recursion depth.
    • Name the trade: Two Sum is O(n²) time with O(1) space, or O(n) time with O(n) space.
  • Spot it in code

    • `seen = {}`, `seen = set()`, `result = []`, `memo = {}` or `visited = set()` that fills inside a loop.
    • Copies: `arr[:]`, `arr[::-1]`, `sorted(arr)`, `list(s)`, `''.join(...)`.
    • A queue or stack that can hold every node (BFS, DFS).
    • Recursion that goes about n levels deep, memoised or not.
  • Memory tricks

    • The backpack: every student who arrives needs one more backpack hook.
    • Pay memory to buy speed: a little extra space often turns O(n²) time into O(n).
    • Hash, copy, memo, visit: four words that usually mean O(n) space.
  • Watch out

    • Recursion depth counts as space, and Python stops near depth 1,000 by default.
    • Slicing in a loop or a recursive call quietly multiplies memory.
    • A counter over a fixed alphabet is O(1), not O(n).