The question basically says it all. Suppose I have a (sorted) list that can contain anywhere from 1K to 1M items. I have a starting index
and an ending index
. If I use the ArrayList.sublist(start, end)
method, is the time complexity O(n) or O(1)? I did check for answers here since I'd think would be a common question, but although I found a duplicate answer for a LinkedList, I couldn't find a specific question about ArrayList. Thanks to all for their answers!
It is of data-type int. Return Type: The element at the specified index in the given list. Note: Time Complexity: ArrayList is one of the List implementations built a top an array. Hence, get(index) is always a constant time O(1) operation.
For ArrayList , insertion is O(1) only if added at the end. In all other cases (adding at the beginning or in the middle), complexity is O(N), because the right-hand portion of the array needs to be copied and shifted. The complexity of a LinkedList will be O(1) both for insertion at the beginning and at the end.
Hence, the time complexity of contains method is O(n) , where n is the number of elements in the list.
Adding an element to beginning of array is O(n) - it would require to shift all the existing elements by one position. All elements in an array list are stored in a contiguous array. If you add more elements than the current size of the array - it will be grown automatically to accommodate the new element.
The sub-list is backed by the source list. There is no copy step, so the time complexity is O(1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With