Junior — Middle
What is the time complexity of accessing an element in a dynamic array?
sobes.tech AI
Answer from AI
In a dynamic array (for example, a slice in Go), access to an element by index has a time complexity of O(1), meaning constant time. This is because elements are stored in a contiguous block of memory, and the address of the required element is calculated directly using a formula:
// Example of accessing a slice element
arr := []int{10, 20, 30, 40}
value := arr[2] // value == 30
Thus, regardless of the size of the array, access to any element is fast and efficient.