- rolls = [101, 104, 102, 104]
- seen = set()
- for r in rolls:
- if r in seen:
- print("Repeat:", r)
- break
- seen.add(r)
- print(len(seen), "stored")
Variables
rolls
Four roll numbers. Did anyone get entered twice?
You just watched seen grow by one item for every new roll number. That extra memory let the program answer "have I met this before?" in one quick look, without scanning the list again.
Quick check
Quick check: Same program, but the list has 5 roll numbers and none repeats. How many items are in seen at the end?
What space complexity counts#
Space complexity is how the memory an algorithm needs grows as the input size n grows. The Big O rules from the last step stay the same: drop constants, keep the biggest term. It counts two kinds of memory. Input space is the input itself, like the rolls list. Auxiliary space is the extra memory your code makes: variables, new lists and sets, and the memory function calls use (more on this below).
Strictly, space complexity counts input space plus auxiliary space. In interviews people usually mean auxiliary space. If you are unsure, say which one you mean.
O(1) space: a few variables#
This finds the highest CGPA in a class. Watch the variable panel: however long the list, the code only ever makes best and c.
- cgpas = [7.8, 9.1, 6.5, 8.4]
- best = cgpas[0]
- for c in cgpas:
- if c > best:
- best = c
- print(best)
Variables
cgpas
Set cgpas to [7.8, 9.1, 6.5, 8.4].
Quick check
Quick check: The class grows from 4 students to 4,000. How much extra memory does this code use now?
Spotting the space#
Look for what your code creates and how big it gets.
| What the code makes | Space |
|---|---|
| A few variables | O(1) |
| A new list or set of up to n items | O(n) |
| n calls waiting inside each other (recursion, below) | O(n) |
| An n by n table (a grid) | O(n²) |
For example, grid = [[0] * n for _ in range(n)] makes n rows of n cells: O(n²) space. That grows fast. For n = 1,000 it has 10 lakh cells. For n = 10,000 it has 10 crore cells. Even at 4 bytes a cell that is 400 MB, more than the 256 MB a coding test often gives your program.
Quick check
Quick check: Your code copies the input list once, then also builds a set of all its items. What is the auxiliary space?
Recursion uses the call stack#
Every function call gets a stack frame: a small block of memory for its parameters, its local variables and the place to come back to. Frames sit on the call stack, and a frame stays until its call returns. So when calls go n deep, n frames sit on the stack at once.
k- def fact(n):
- if n <= 1:
- return 1
- return n * fact(n - 1)
- k = 4
- print(fact(k))
Variables
None yet
Line 1 runs.
At the deepest point, four calls are waiting at the same time:
Drag k to 1 and see the edge case: one call, one frame, no waiting.
Quick check
Quick check: How many frames are needed at the deepest point of fact(1000)?
Recursive binary search: O(log n) space#
Binary search works on a sorted list. It looks at the middle item. If the target is bigger, it searches only the right half, else the left half. lo and hi mark the part still left to search. When lo passes hi, nothing is left, so the target is not there. Each call halves the range, so calls go only about log n deep.
target- target = 9
- rolls = [1, 3, 4, 6, 7, 8, 9]
- def find(lo, hi):
- if lo > hi:
- return -1
- mid = (lo + hi) // 2
- if rolls[mid] == target:
- return mid
- if rolls[mid] < target:
- return find(mid+1, hi)
- return find(lo, mid-1)
- print(find(0, 6))
Variables
- target
- 9 (just changed)
Pick a target. Try 6 and 10 on the slider.
At the deepest point, three find frames were open at once. Now drag target to the edges: 6 is the very middle, and 10 is not in the list.
Quick check
Quick check: How many find frames are open at once for target 6, and for 10?
The time-space trade-off#
Back to the duplicate check. Without a set, you compare every pair of roll numbers. Watch how many comparisons it makes, and how few variables.
- rolls = [101, 104, 102, 104]
- n = len(rolls)
- found = False
- for i in range(n):
- for j in range(i + 1, n):
- if rolls[i] == rolls[j]:
- found = True
- print(found)
Variables
rolls
Set rolls to [101, 104, 102, 104].
| Approach | Time | Extra space |
|---|---|---|
| Compare every pair | O(n²) | O(1) |
| Set of seen rolls | O(n) on average | O(n) |
The set pays memory to save time. A set finds an item in about one step however big it gets (it uses hashing, which comes later). Rarely it is slower, so we say "on average". This is a time-space trade-off, and it shows up everywhere, like remembering answers you already worked out (this is called caching).
Quick check
Quick check: A placement drive has 1 lakh roll numbers. About how many comparisons does the every-pair method make?
One last check#
Quick check
Quick check: A function first builds a list of n items. Then it calls a recursive helper that goes n calls deep, and each call keeps two variables. What is the auxiliary space?
Next is the readiness check, a short quiz on reading code and judging its time and space before stage 2 starts with searching.