Space complexity
Space complexity is how extra memory grows with n. In Rust that includes heap allocations, recursion depth, and the hidden buffers inside collect and clone.
Detailed Explanation
An algorithm that walks a slice with a few locals is O(1) extra space. An algorithm that collects a second Vec is O(n). A recursive walk of a balanced tree is O(log n) stack frames; a recursive walk of a linked list is O(n) stack frames and will overflow the stack on a long list.
Rust makes the heap visible. Vec, String, HashMap, Box, to_owned, clone of an owned buffer — those allocate. A function that takes &[T] and returns Vec<T> always has a space cost of O(n) plus any spare capacity. A function that returns impl Iterator can be O(1) extra space until the caller collects.
Capacity is part of space. A Vec that grew by doubling may hold twice the elements you see in len. shrink_to_fit returns that spare; it is rarely worth it unless you are about to keep the vector for a long time. HashMap also over-allocates to keep load factor down.
Stack versus heap is a space question. A [u8; 1_000_000] local is a megabyte of stack and can crash a thread with an 8 MiB (or smaller) stack. The same buffer in a Vec lives on the heap. Recursion is stack. An explicit Vec as a stack is heap and can grow.
Sharing reduces space. Arc<[T]> lets many owners see one allocation. Cow avoids a copy until a write. Those are O(1) extra space for the pointer, not O(n) per owner, unless someone clones the inner data.
When you reason about space: say whether you mean extra space beyond the input, whether recursion counts, and whether you are counting capacity or length. When you leak space: forgotten collects in a loop, clone in a map adapter, growing a Vec that you never clear.
Code Examples
fn doubled(xs: &[i32]) -> Vec<i32> {
xs.iter().map(|x| x * 2).collect() // O(n) extra space
}
fn sum(xs: &[i32]) -> i32 {
xs.iter().sum() // O(1) extra space
}
fn main() {
let xs = [1, 2, 3];
println!("{:?}", doubled(&xs)); // prints: [2, 4, 6]
println!("{}", sum(&xs)); // prints: 6
}Common Gotchas
Recursion depth is space
A recursive DFS on a degenerate graph is O(n) stack. Use an explicit `Vec` stack if n can be large.
`collect` in a loop allocates every iteration
Build one `Vec` and `clear`, or drain into a reused buffer.
Iterator chains can be O(1) until collected
Do not `collect` between adapters unless you need random access or multiple passes.
Capacity is real memory
`len == 0` on a `Vec` that once held a million items may still hold a million slots until you shrink or drop it.