Space complexity
Space complexity describes how extra memory an algorithm uses as the input grows. Auxiliary space usually excludes the input itself: an in-place swap is O(1) extra; a copy of the input is O(n).
Detailed Explanation
A function that sorts a slice with sort.Ints uses a small, fixed amount of extra memory. A function that builds a map[int]struct{} of every ID uses O(n) extra words. Both might be O(n log n) time. Space is the other axis.
Auxiliary vs total. Interview answers usually mean auxiliary: what you allocate beyond the arguments. make([]int, n) inside the function is O(n) auxiliary. The input []int the caller already holds is not counted twice. Total space includes the input.
Go allocations that count. make([]T, n), make(map[K]V, n), append that grows past cap, []byte(s) copies, closures that capture large slices, and recursion frames. A goroutine's stack starts small and grows; a recursive DFS on a chain of n nodes is O(n) stack. An explicit slice used as a stack is also O(n) but does not risk a stack overflow the same way.
Sharing is not free in the other direction. Returning s[i:j] is O(1) auxiliary and keeps the whole backing array alive. That is good for space in the Big-O sense and bad if the array is huge. Copying the window is O(j-i) space and lets the large array be collected.
In-place in Go. Swapping elements in the caller's slice is O(1) extra. append on a slice you do not own may reallocate and then you are not in-place for the caller unless you return the new header. Document whether you mutate the input.
What it costs to ignore it. Loading a 2 GiB file into a []byte then into a string then into a []rune is three copies. Streaming with bufio is O(1) extra relative to the file. Prefer streaming APIs when n is "the whole dataset," and a full slice when n is "this request's rows."
Code Examples
package main
import "fmt"
func unique(ids []int) []int {
// O(n) auxiliary: the set and the output
seen := make(map[int]struct{}, len(ids))
out := make([]int, 0, len(ids))
for _, id := range ids {
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
out = append(out, id)
}
return out
}
func swapEnds(s []int) {
// O(1) auxiliary: mutates in place
if len(s) < 2 {
return
}
s[0], s[len(s)-1] = s[len(s)-1], s[0]
}
func main() {
s := []int{1, 1, 2}
fmt.Println(unique(s))
swapEnds(s)
fmt.Println(s)
}Common Gotchas
Returning a subslice is `O(1)` space and can pin `O(n)` unused bytes
copy when the source is large and long-lived.
Recursion uses stack space
a linear chain of `n` calls is `O(n)` and can crash a goroutine if `n` is huge.
A second `[]byte(s)` is another copy
reuse buffers (`sync.Pool`, or a sized `[]byte` you pass in) on hot paths.
`map` overhead is larger than `n` words
each key has bucket overhead. For dense integer keys, a slice can use less space.