Junior — Middle
What is the time complexity of obtaining an element by index in a linked list?
sobes.tech AI
Answer from AI
The time complexity of accessing an element by index in a linked list is O(n), where n is the position of the element.
This is because a linked list does not support direct index-based access like an array. To access the element at index i, you need to traverse from the beginning of the list through i elements.
Example in Java:
class Node {
int value;
Node next;
}
int getElementAt(Node head, int index) {
Node current = head;
int count = 0;
while (current != null) {
if (count == index) {
return current.value;
}
current = current.next;
count++;
}
throw new IndexOutOfBoundsException();
}
Thus, index access in a linked list is inefficient for large index values.