Junior
What is the worst-case time complexity of the add() method for ArrayList?
sobes.tech AI
Answer from AI
Amortized constant time O(1).
In most cases, add() is performed in constant time because the new element is simply added to the end of the existing internal array.
The worst case occurs when the internal array reaches capacity. In this case, ArrayList creates a new, larger array (usually 1.5 times the current size), copies all elements from the old array to the new one, and then adds the new element. This copying operation takes time proportional to the current number of elements (N), resulting in a time complexity of O(N).
However, since such resizing happens rarely and is spread out over many add() calls, the average time complexity of add() (amortized) remains constant.