Accessing array elements in Go - Time & Space Complexity
When we access elements in an array, we want to know how long it takes as the array grows.
We ask: Does it take longer to get an element if the array is bigger?
Analyze the time complexity of the following code snippet.
package main
import "fmt"
func main() {
arr := [5]int{10, 20, 30, 40, 50}
fmt.Println(arr[2])
}
This code creates an array and prints the element at index 2.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing a single element by index.
- How many times: Exactly once in this example.
Accessing an element by index takes the same time no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the array grows larger.
Time Complexity: O(1)
This means accessing any element takes a fixed amount of time, no matter the array size.
[X] Wrong: "Accessing an element takes longer if the array is bigger."
[OK] Correct: Arrays store elements in contiguous memory, so the computer can jump directly to any element quickly.
Knowing that array access is fast helps you choose the right data structure and explain your choices clearly in interviews.
"What if we used a linked list instead of an array? How would the time complexity of accessing an element change?"