Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to apply binary search O(log n) on a sorted linked list?

Recently I came across one interesting question on linked list. Sorted singly linked list is given and we have to search one element from this list.

Time complexity should not be more than O(log n). This seems that we need to apply binary search on this linked list. How? As linked list does not provide random access if we try to apply binary search algorithm it will reach O(n) as we need to find length of the list and go to the middle.

Any ideas?

like image 861
Umesh K Avatar asked Mar 12 '11 06:03

Umesh K


People also ask

Can you binary search a sorted linked list?

Binary Search is divide and conquer approach to search an element from the list of sorted element. In Linked List we can do binary search but it has time complexity O(n) that is same as what we have for linear search which makes Binary Search inefficient to use in Linked List.

Can binary search run in O log N time on a doubly linked list?

It's technically correct to say that the runtime of binary search on a doubly-linked list is O(n log n), but that's not a tight upper bound. Using a slightly better implementation of binary search and a more clever analysis, it's possible to get binary search to run in time O(n).

How does binary search work on sorted list?

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.

Why is binary search not suitable for sorted linked list?

A linked list only allows sequential access, so binary search is impossible even if the list is sorted.


2 Answers

It is certainly not possible with a plain singly-linked list.

Sketch proof: to examine the last node of a singly-linked list, we must perform n-1 operations of following a "next" pointer [proof by induction on the fact that there is only one reference to the k+1th node, and it is in the kth node, and it takes a operation to follow it]. For certain inputs, it is necessary to examine the last node (specifically, if the searched-for element is equal to or greater than its value). Hence for certain inputs, time required is proportional to n.

You either need more time, or a different data structure.

Note that you can do it in O(log n) comparisons with a binary search. It'll just take more time than that, so this fact is only of interest if comparisons are very much more expensive than list traversal.

like image 157
Steve Jessop Avatar answered Sep 21 '22 23:09

Steve Jessop


You need to use skip list. This is not possible with a normal linked list (and I really want to learn if this is possible with normal list).

like image 39
taskinoor Avatar answered Sep 21 '22 23:09

taskinoor