Junior — Middle
What is the reason that slice operations can have a time complexity of O(1)?
sobes.tech AI
Answer from AI
In Go, slices (slices) are a structure that contains a pointer to an array, a length, and a capacity. Operations on slices, such as obtaining a sub-slice, have a time complexity of O(1), because:
- When creating a slice from an existing slice or array, data is not copied; instead, a new slice is created with a pointer to the same array.
- The operation simply creates a new structure with a starting index and length, without iterating over elements.
For example:
arr := []int{1, 2, 3, 4, 5}
slice := arr[1:3] // Creates a new slice pointing to elements with indices 1 and 2
Thus, creating a slice is just creating a structure with a pointer and metadata, which ensures O(1) time complexity.