Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of Java's ArrayList.sublist(startIndex, endIndex) method?

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!

like image 845
Grace F. Avatar asked May 15 '18 01:05

Grace F.


People also ask

What is the time complexity of ArrayList get method?

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.

What is the complexity of the ArrayList and LinkedList?

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.

What is complexity Big O notation of ArrayList contains () method?

Hence, the time complexity of contains method is O(n) , where n is the number of elements in the list.

What is the time complexity of adding an element to an ArrayList?

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.


1 Answers

The sub-list is backed by the source list. There is no copy step, so the time complexity is O(1).

like image 120
user207421 Avatar answered Sep 18 '22 08:09

user207421