Junior — Middle
What is the time complexity of retrieving an element from an array by index?
sobes.tech AI
Answer from AI
The temporary complexity of retrieving an element from an array by index is O(1), which is constant. This is because arrays in memory are stored as a contiguous block, and access to an element by index is done directly through address calculation: base address of the array plus index multiplied by element size.
Example in Go:
arr := []int{10, 20, 30, 40}
value := arr[2] // get element at index 2, value == 30
This access does not depend on the size of the array, making it very efficient.