Skip to content
Learn Netverks

Lesson

Step 8/36 22% through track

space-complexity

Space complexity

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Space complexity: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Wrong complexity estimates ship slow APIs and fail interviews—analysis must precede micro-optimizations.

You will apply Space complexity in contexts like: API design reviews, capacity planning, and whiteboard interview loops.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

When you can explain the previous lesson's ideas in your own words.

Space complexity measures extra memory beyond the input. An in-place loop uses O(1) auxiliary space; building a frequency table uses O(k) for k distinct keys.

Auxiliary vs total

  • Auxiliary space — extra allocations (hash map, recursion stack)
  • Total space — includes input storage (often not counted in interview auxiliary answer)

Recursion stack

DFS recursion depth h uses O(h) stack frames—deep skewed trees can overflow stack; iterative BFS uses explicit queue instead.

Frequency map space

#include 
#include 
#include 

int main() {
    std::vector a = {1, 2, 1, 3, 2, 1};
    std::unordered_map freq;
    for (int x : a) freq[x]++;
    std::cout << "distinct keys = " << freq.size() << " (O(k) extra)\n";
    return 0;
}

Important interview questions and answers

  1. Q: Two-sum with hash map space?
    A: O(n) for storing seen values in worst case.
  2. Q: In-place sorting?
    A: Some algorithms O(1) auxiliary; merge sort needs O(n) temp array.

Self-check

  1. Define auxiliary space complexity.
  2. DFS on tree of height h uses what stack space?

Tip: State auxiliary space separately from input size when asked in interviews.

Interview prep

Auxiliary space?

Extra memory beyond input—hash table, recursion stack, DP table.

Two-sum space?

O(n) for hash map of seen values.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Auxiliary space?
  • Recursion stack?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump