Sobes.tech
Junior — Middle

What is the time complexity of adding an element to a dynamic array?

sobes.tech AI

Answer from AI

Adding an element to a dynamic array typically has an amortized time complexity of O(1).

Explanation:

  • If there is free space in the array, the element is added in constant time.
  • If there is no space, the array allocates a new block of memory of larger size (usually twice as large), copies the old elements, and adds the new one.

Although the expansion operation takes O(n), it does not happen often, so the average (amortized) complexity of adding remains O(1).

Example in Go using slices:

var arr []int
arr = append(arr, 10) // adding an element

append will automatically expand the slice if necessary.