Junior — Middle
How is the time complexity of adding an element to the end of a Slice array type evaluated?
sobes.tech AI
Answer from AI
Adding an element to the end of a slice in Go usually has an amortized time complexity of O(1). This is because slices have an internal array with a certain capacity. If the capacity is not exceeded when adding an element, the operation simply adds the element and takes constant time.
However, when the internal array's capacity is exhausted, a new array with increased capacity (usually twice as large) is allocated, the old elements are copied to the new array, and the new element is added. This operation takes O(n) time, where n is the current size of the slice.
Thus, on average (amortized), adding an element is O(1), but in the worst case, it is O(n).