One Step, Any Size
O(1) means constant time: the operation takes the same number of steps whether the input has 5 elements or a million. The work does not grow at all.
This is the best complexity there is. Typical O(1) operations in Go are: reading a slice element by index, reading a map value by key, len(), appending one element, and simple math.
Note what O(1) does not mean: it does not mean "fast", it means "does not get slower when the input grows". One constant step can still be a slow step — but it stays one step.
Slice and Map Lookups
A slice element lives at a known position in memory, so words[2] is one jump — the computer does not walk through the elements before it. The same read costs the same in a slice of one million elements.
A map lookup like ages["Ben"] also takes constant time on average: the key tells the map directly where the value is stored. The lookup returns value, ok, and ok is false when the key is missing.
Read an element by index
The program reads one element from a 5-element slice and one from a slice with a million elements. Both reads are a single step — the slice length plays no role.
Output: Go program and captured output
package main
import "fmt"
func main() {
words := []string{"one", "two", "three", "four", "five"}
big := make([]int, 1000000)
for i := range big {
big[i] = i * 2
}
// One step each, no matter how long the slice is.
fmt.Println(words[2])
fmt.Println(big[999999])
}
Read a value by key
ages["Ben"] finds 25 directly. The missing key "Dan" returns the zero value 0 and ok == false — still in constant time.
Output: Go program and captured output
package main
import "fmt"
func main() {
ages := map[string]int{"Ana": 30, "Ben": 25, "Cleo": 41}
age, ok := ages["Ben"]
fmt.Println(age, ok)
age, ok = ages["Dan"]
fmt.Println(age, ok)
}
Appending and Simple Math
append() adds one element at the end of a slice. Most of the time that is one step. (Once in a while the slice must grow and gets copied, but averaged out the cost per append stays constant.)
All the small operations — assignments, additions, comparisons, swapping two values — are O(1) too. They are the "steps" that all the other complexity classes are counted in.
Append one element
append() puts "yellow" at the end. The cost does not depend on how many colors are already in the slice.
Output: Go program and captured output
package main
import "fmt"
func main() {
colors := []string{"red", "green", "blue"}
fmt.Println("before:", colors, "len:", len(colors))
colors = append(colors, "yellow")
fmt.Println("after: ", colors, "len:", len(colors))
}
Swap two values
a, b = b, a swaps the two values in one constant-time step — no helper variable needed.
Output: Go program and captured output
package main
import "fmt"
func main() {
a, b := 1, 2
fmt.Println("before:", a, b)
a, b = b, a
fmt.Println("after: ", a, b)
}