Junior — Middle
What is the time complexity of adding an element to the end of an ArrayList?
sobes.tech AI
Answer from AI
The average time complexity of adding an element to the end of an ArrayList is O(1) — amortized constant time.
This is because ArrayList stores elements in a fixed-size array. When adding an element, if there is free space in the array, the element is simply placed in the next slot.
However, if the array is full, a resize operation occurs — a new larger array is created, and all elements are copied into it. This operation takes O(n) time, where n is the number of elements.
Example:
ArrayList<Integer> list = new ArrayList<>();
list.add(1); // O(1)
list.add(2); // O(1)
// When the array reaches capacity, it is resized — O(n)
Thus, the average addition complexity is O(1), but in the worst case — O(n).