Search code examples
javaalgorithmlinked-listtime-complexitysortedlist

Time complexity of inserting a node in a sorted linked list


What is the time complexity of inserting a node in a sorted linked list in Java? Is there an algorithm with complexity less than O(n)?


Solution

  • If all you have is a linked links and you're starting from the head, in the worst case you have to iterate over the entire list to find the insertion point. This gives O(n) worst-case time.

    Something like a skiplist could give O(log n) insertion. However, that's a different data structure to what you're asking about (and so are trees etc).