0

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)?

4
  • Usually not, unless there you have references to several nodes in the list. Commented Apr 17, 2017 at 16:52
  • 1
    With only O(1) references into the list (e.g. head + tail), then no. Commented Apr 17, 2017 at 16:54
  • @OliverCharlesworth there is no pointers in Java. Commented Apr 17, 2017 at 16:55
  • 2
    @Omore - NullPointerException disagrees ;) (Didn't notice that this was marked Java...) Commented Apr 17, 2017 at 16:57

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.