- Your first loop for iterating
items list: complexity is O(n)
- Insert each item to end of list
lessItems: in normal array it will be O(n) as others said. But Java implements for ArrayList using amortized array. This means when inserting at the end of array, algorithm only costs Amortized O(1). Or you can say O(1)
So complexity of your code is: O(n) * amortized O(1). In short is O(n)
Another reference:
dynamic array
Additional note 1:
If complexity of inserting at the end of array is O(N), so the total complexity is O(N^2), not O(2*N) as other answers said. Because the total complexity for inserting would be: 1 + 2 + 3 + ...+ n = n*(n+1)/2
Addtional Note 2:
as official document states:
The size, isEmpty, get, set, iterator, and listIterator operations run
in constant time. The add operation runs in amortized constant time,
that is, adding n elements requires O(n) time. All of the other
operations run in linear time (roughly speaking). The constant factor
is low compared to that for the LinkedList implementation.
Additional note 3:
Here is the logic of grow method that I have taken from official java source code:
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
As the source code has said, when program add element that make size of array larger than current capacity, Array will be grown. new size of grown array will be:
int newCapacity = oldCapacity + (oldCapacity >> 1);
This is a trick that make inserting is amortized O(1)
O(n). Please see my answer.O(n). After that you have a number (not 2) of constant time operations. They shouldn't be saying the way @Elliott did in the previous comments. It's incorrect and inaccurate to sayO(n) + O(n)because the second complexity exists internal to the first (IOW, it's not addition but multiplication of constant terms); it'scn =O(n)`.O(n) + O(n)? There's other time left out.