Junior — Middle
How to evaluate the time complexity of adding an element to an ArrayList?
sobes.tech AI
Answer from AI
The amortized time complexity of adding an element to an ArrayList is usually O(1). This is because when adding an element to the end of the list, if the internal array has free space, the element is simply placed in the next slot.
However, if the internal array is full, it is expanded (elements are copied to a new larger array), which takes O(n) time, where n is the current size of the list.
Therefore:
- On average (amortized), adding is O(1)
- In the worst case (when expanding the array), it is O(n)
Example:
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // Amortized O(1)