Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Big-O and Complexity

    Space Complexity

    Space complexity — how much extra memory an algorithm uses as n grows, in Big-O.

    Chapter 6 of 113 min read

    The Plain Picture#

    Two ways to count how many different words are in a book: keep a notebook listing every word you've seen (the notebook grows with the book), or re-read the whole book for each word (no notebook, but far slower). Memory is the second resource — and it's limited too.

    The Real Names#

    • Space complexity = how much extra memory an algorithm uses as n grows, in Big-O.

    • Auxiliary space = memory beyond the input itself. Interviewers usually mean auxiliary space; say which one you mean.

    • In-place algorithm = O(1) auxiliary space (it modifies the input directly, like reversing an array by swapping ends).

    • Recursion uses space too: every active call is a stack frame (Operating Systems Ch 6). A recursion that goes n levels deep uses O(n) stack space — even if it allocates nothing else. Deep enough, it's a StackOverflowError.

    Under the Hood#

    CodeExtra space
    a few int variablesO(1)
    a copy of the array / a HashSet of all itemsO(n)
    an n × n grid (e.g. a DP table)O(n²)
    recursion n levels deep (e.g. a naïve recursive linked-list walk)O(n) — the call stack
    recursion log n levels deep (binary search written recursively, balanced tree)O(log n)

    Output doesn't usually count: if a problem asks you to return all n² pairs, the output is O(n²) no matter what; say "O(1) extra space besides the output".

    Memory limits are real: LeetCode typically allows a few hundred MB. An int[100_000_000] is 400 MB (How Computers Work Ch 2), and a boolean[n][n] for n = 100,000 is 10 GB — too big. Checking space is part of checking a solution.

    Check yourself

    3 questions
    1

    What's auxiliary space?

    Show answer

    Extra memory used beyond the input itself.

    2

    A recursive function calls itself n times in a chain, using only a few variables per call. What's its space complexity?

    Show answer

    O(n) — n stack frames at the deepest point.

    3

    What's the space complexity of solution B in Chapter 4 (sort a copy)? Of sorting the original array in place instead?

    Show answer

    O(n) for the copy. In place it's O(1) extra from our code (Java's sort itself may use O(log n) stack, or O(n) for object arrays).