Junior — Middle
What is the algorithmic complexity of adding an element to the end of an ArrayList?
sobes.tech AI
Answer from AI
Adding an element to the end of an ArrayList has an amortized complexity of O(1). This is because, when adding, the element is simply placed in the next free slot of the array.
However, if the internal array is full, it is expanded (usually by 1.5-2 times), which requires copying all elements to a new array. At this point, the add operation takes O(n), where n is the current size of the list.
Thus, the amortized complexity of adding is O(1), but in the worst case, it is O(n).