Sobes.tech
Junior — Middle

How is the time complexity determined when 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:

  • If the internal array of the ArrayList has free space, the new element is simply written to the next position — this operation takes constant time O(1).
  • If the internal array is full, it is expanded: a new larger array is created, and all elements are copied there. This operation takes O(n), where n is the current size of the list.

However, expansion does not occur with every addition, but only periodically, so the average (amortized) complexity of adding remains O(1).

Example:

ArrayList<Integer> list = new ArrayList<>();
list.add(10); // Amortized O(1)