Sobes.tech
Junior — Middle

In what situations can adding an element to the end of an ArrayList have a time complexity of O(n)?

sobes.tech AI

Answer from AI

Adding an element to the end of an ArrayList usually has an amortized time complexity of O(1), but in some cases, it can be O(n). This occurs when the internal array that stores the elements is full and needs to be expanded.

When adding a new element:

  • If there is enough space, the element is simply added — O(1).
  • If there is no space, a new array of larger size (usually 1.5-2 times larger) is created, and all existing elements are copied to the new array — this operation is O(n).

Thus, adding an element can have a time complexity of O(n) precisely at the moment of expanding the internal array.