Junior — Middle
What is the time complexity of inserting an element at the beginning of a dynamic array ArrayList?
sobes.tech AI
Answer from AI
Inserting an element at the beginning of a dynamic array (for example, ArrayList in Java) has a time complexity of O(n), where n is the number of elements in the array.
This is because when inserting at the beginning, all existing elements need to be shifted one position to the right to make space for the new element. The process of copying elements takes linear time.
Example:
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
// Insert at the beginning
list.add(0, 0); // shifts all elements to the right
Thus, inserting at the end is usually faster (amortized O(1)), while at the beginning — O(n).