Junior — Middle
How quickly can you find an element in a linked list?
sobes.tech AI
Answer from AI
In a linked list, searching for an element by value requires sequential traversal of nodes, starting from the head of the list, until the desired element is found or the end of the list is reached. This means the worst-case search time is O(n), where n is the number of elements in the list.
Unlike arrays, where direct access by index is O(1), linked lists do not support random access, so efficient search is not possible without additional data structures.
Example of traversing a linked list in Java:
class Node {
int value;
Node next;
Node(int value) { this.value = value; }
}
boolean contains(Node head, int target) {
Node current = head;
while (current != null) {
if (current.value == target) {
return true;
}
current = current.next;
}
return false;
}