Sobes.tech
Junior — Middle

What is the time complexity level of adding an element to the end of an array using a slice?

sobes.tech AI

Answer from AI

In Go, the operation of adding an element to the end of a slice (append) has an amortized time complexity of O(1).

Explanation:

  • If the slice has enough allocated capacity (capacity), then adding an element is simply a matter of writing to the next free index — this operation takes constant time.

  • If the capacity is insufficient, a new larger array is allocated, old elements are copied, and the new element is added — this operation takes O(n), where n is the current size of the slice.

However, since such reallocations do not occur with every addition but only periodically, the average (amortized) complexity of adding remains O(1).

What is the time complexity level of adding an… - sobes.tech