Time complexity
Time complexity describes how the number of steps in an algorithm grows as the input grows. Big-O names the dominant term: O(1), O(n), O(n log n), O(n²).
Detailed Explanation
You write a loop over n users and, inside it, another loop over the same n users. That is about n² comparisons. Doubling the user list quadruples the work. Time complexity is how we say that without running a stopwatch on every size.
Count operations that grow. A single map lookup is treated as O(1) average. A range over a slice of length n is O(n). Sorting with sort.Slice is O(n log n). Nested loops over the same n are O(n²). Constants and slower-growing terms drop: 3n + 10 is O(n).
Go-specific costs people forget. append in a loop that starts from nil is amortized O(1) per append, O(n) for n appends. s += chunk on a string is O(n²) over n chunks of similar size. len(s) on a slice or string is O(1). Ranging a map is O(n) in the number of keys. A method call through an interface is still O(1) work for the call itself; the complexity is whatever the method does.
Average vs worst. Hash map lookup is average O(1) and worst O(n) if every key collides. Go's map is fine for ordinary keys; do not treat a map as O(n) in an interview unless you are talking about worst case. Binary heap push is O(log n) worst. Quicksort in sort.Sort for interfaces is implementation-defined; sort.Slice uses a pattern-defeating quicksort that is O(n log n) in practice.
Measure when the constant matters. O(n) with a huge constant can lose to O(n log n) for the sizes you have. testing.B and pprof answer that. Big-O answers "what happens at 10× the data." Both belong in a design conversation.
What it costs to ignore it. A handler that does O(n²) work per request is fine at 20 rows and dead at 20,000. Write the complexity next to any function that takes a slice or walks a graph, even if only in a comment, so the next change does not nest another loop without noticing.
Code Examples
package main
import "fmt"
func hasPair(ids []int) bool {
// O(n²): every i compared to every later j
for i := range ids {
for j := i + 1; j < len(ids); j++ {
if ids[i] == ids[j] {
return true
}
}
}
return false
}
func hasPairFast(ids []int) bool {
// O(n) average: one pass, map lookups
seen := make(map[int]struct{}, len(ids))
for _, id := range ids {
if _, ok := seen[id]; ok {
return true
}
seen[id] = struct{}{}
}
return false
}
func main() {
fmt.Println(hasPair([]int{1, 2, 1}), hasPairFast([]int{1, 2, 1}))
}Common Gotchas
`len` is `O(1)`, but `utf8.RuneCountInString` is `O(n)`
do not treat "length of text" as one cost.
Amortized `append` is `O(1)` per call only if you keep the returned slice
discarded reallocations still copy.
Big-O hides constants
profile before you rewrite a clear `O(n)` into a clever `O(n)`.
Nested `range` over the same slice is `O(n²)` even if each body is one line
Nested `range` over the same slice is `O(n²)` even if each body is one line