5

I am confused over the searching complexity of LinkedList in java. I have read that time complexity to search an element from a LinkedList is O(n). say for example,

LinkedList<String> link=new LinkedList<String>();
    link.add("A");
    link.add("B");
    link.add("C");
    System.out.println(link.get(1));

Now, from here by get(index) method we can say that to search an element It should take O(1) times. But I have read that it will take O(n). Can anybody help me out to get clear concept?

Cœur
  • 37,241
  • 25
  • 195
  • 267
stumbler
  • 647
  • 3
  • 11
  • 26

3 Answers3

7

Access in a linked list implementation, like java.util.LinkedList, is O(n). To get an element from the list, there is a loop that follows links from one element to the next. In the worst case, in a list of n elements, n iterations of the loop are executed.

Contrast that with an array-based list, like java.util.ArrayList. Given an index, one random-access operation is performed to retrieve the data. That's O(1).

erickson
  • 265,237
  • 58
  • 395
  • 493
  • As randomAccess is in ArrayList it takes constant time to search an element in worst case. LinkedList there is no RandomAccess interface, so in worst case it has to search the whole list. – stumbler Feb 18 '16 at 20:29
  • Yes, that's right. But `LinkedList` doesn't implement the `RandomAccess` interface because it doesn't support random access. The way you said that makes it sound like the effect is the cause. – erickson Feb 18 '16 at 20:36
  • Not the whole list but a half of the list – MaxZoom Feb 18 '16 at 20:37
1

A linked list is as such, a list of items that are linked together by a means such as a pointer. To search a linked list, you are going to iterate over each item in the list. The most time this will take, will be T(n) where n is the length of your list.

A big-O notation stands for the upper bounds or the worst case scenario.

If you are searching for an item at index 1 it will finish almost immediately, T(1), since it was the first item in the list. If you are to search for the n^th item it will take T(n) time, thus staying in O(n).

A visual representation of a linked list:

[1] -> [2] -> [3] -> [4] -> ... [n-1] -> [n]

An example of what a get() method might look like

get(int i)
{ 
 Node current = head
 while (i > 0)
 {
   current = current.getNext()
   i--
 }
 return current
}

As you see, it iterates over each node within the list.

DarkJade
  • 270
  • 1
  • 8
0

The Ordo function means a maximal approximation. So it is O(n) because if the list has n entries and you want to get the last entry, then the search goes through n items.

On the other hand, lookup for an ArrayList is O(1), because the lookup time is close to constant, regardless the size of the list and the index you are looking for.

erosb
  • 2,943
  • 15
  • 22