Junior — Middle
What is the time complexity of removing an element from the middle of an array implemented via ArrayList?
sobes.tech AI
Answer from AI
In Java, the ArrayList class is implemented based on a dynamic array. When removing an element from the middle of the array, all subsequent elements are shifted one position to the left to fill the gap.
Therefore, the time complexity of removing an element from the middle of an ArrayList is O(n), where n is the number of elements after the removed element.
Example:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
list.remove(2); // removes the element at index 2 (the number 3)
// elements 4 and 5 shift to the left
Removing from the end of the list is an O(1) operation, as no shifting is required.