Sobes.tech
Junior — Middle

What is the time complexity of searching for an element in a list by index?

sobes.tech AI

Answer from AI

The element access operation in a slice in Go (e.g., slice[index]) has a time complexity of O(1), meaning it executes in constant time. This is because a slice in Go is a structure with a pointer to an underlying array, along with length and capacity, and accessing an element by index is a direct memory address calculation.

Example:

package main
import "fmt"

func main() {
    s := []int{10, 20, 30, 40}
    fmt.Println(s[2]) // Outputs 30
}

Thus, element lookup by index in a list (slice) in Go is very efficient.

What is the time complexity of searching for an… - sobes.tech