Java.Collections.What is the worst case running time of the contains() method for an element that is in a LinkedList?

🔍 contains() in a LinkedList

What does it do?

list.contains(element) checks whether the list contains a specific element. Internally, it:

  1. Starts from the head of the linked list.
  2. Iterates through each node.
  3. Uses .equals() to compare each node’s value with the target.

⏱️ Worst-case running time?

✅ Time complexity: O(n)

  • n = number of elements in the list.
  • Worst case: the element is at the end or not present at all → the method must check every single node.

Even if the element is present, if it’s near the end, the search still takes almost full traversal.


🧠 Key point:

Unlike ArrayList, LinkedList cannot jump to the middle using indices. It has to walk node by node from the beginning.


🧪 Example:

LinkedList<String> list = new LinkedList<>();
list.add("a");
list.add("b");
list.add("c");
// contains("c") → O(n), because it might need to check all elements

Summary:

OperationLinkedList.contains()
Best CaseO(1) – if it’s the first element
Worst CaseO(n) – if it’s last or not present
This entry was posted in Без рубрики. Bookmark the permalink.