Sub topic 4
Reaching the i-th element
This chapter assumes you can write loops and functions, understand references (a variable that points to an object), and know that O(1) means constant time and O(n) means time that grows with input size. It covers one operation: getting the element at position i.
The working model
An array stores its elements side by side in one block of memory. Every slot has the same size. To find slot i, the machine computes an address:
address = start + i * element_sizeThat is one multiplication and one addition, whatever the value of i. So indexing is O(1).
A linked list stores each element in a separate node. A node holds a value and a reference to the next node. The list keeps only a reference to the first node, called the head. Nothing in memory tells you where node i lives, so you start at the head and follow next links i times. That is i hops, so indexing is O(n) in the worst case.
Seeing it in code
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def get(head, index):
node = head
for _ in range(index):
if node is None:
break
node = node.next
if node is None:
raise IndexError(index)
return node.value
head = Node(10, Node(20, Node(30)))
print(get(head, 2)) # 30, reached by following 2 links
items = [10, 20, 30]
print(items[2]) # 30, reached by direct index arithmeticBoth calls return 30. The list lookup does a fixed amount of work. The get function runs its loop once per hop, so its cost grows with index.
Python's built-in list is a dynamic array, so items[2] is the direct lookup described above.
Cost by position
For a linked list, the cost depends on where the target sits.
| Target position | Array | Singly linked list |
|---|---|---|
| First element | O(1) | O(1) |
| Middle element | O(1) | O(n) |
| Last element | O(1) | O(n), or O(1) with a tail pointer |
| Element at an unknown position | O(n) search | O(n) search |
The last row matters. Access by index and search by value are different operations. If you do not know where a value is, both structures must check elements one by one, so both cost O(n). Arrays only win when you already know the index.
A tail pointer is a second reference the list keeps to its last node. It makes the last element cheap to reach. It does not help with middle positions, and a later chapter covers it.
Common errors
- Assuming
list[i]on a linked list is cheap. Some libraries give linked lists anat(i)orget(i)method that looks like array indexing. It still walks the nodes. Calling it inside a loop turns an O(n) pass into O(n²). - Indexing in a loop over a linked list. Writing
for i in range(n): get(head, i)costs 0 + 1 + 2 + ... + (n-1) hops, which is O(n²). Walk once with a node reference instead. - Forgetting the bounds check. Walking past the end gives
None, and reading.nextor.valueon it raises anAttributeError. Thegetfunction above checks for this and raisesIndexError. - Treating "constant time" as "fast". Array indexing is O(1), but that says nothing about how large the constant is. Later chapters on cache locality explain why this matters.
A better way to visit every element of a linked list:
node = head
while node is not None:
print(node.value)
node = node.nextThis does n hops in total, not n²/2.
What this means for choosing
If your workload frequently asks for "the element at position i" with varied i, such as binary search, lookup tables, or indexing into a sorted sequence, an array is the natural fit. Binary search on a linked list gains nothing, because finding the midpoint already costs O(n).
If your workload only walks the sequence from the front, or only touches the ends, the lack of random access costs you little. Other factors then decide, and the next chapters cover them.
Exercise
A linked list holds 1,000 nodes. You run for i in range(1000): get(head, i) using the get function above. Roughly how many next hops happen in total, and how would you reduce this to about 1,000?
Show answer
Call i performs i hops, so the total is 0 + 1 + ... + 999 = 499,500 hops, which is O(n²). Walk the list once with node = node.next inside a while node is not None loop. That makes one hop per element, about 1,000 in total.
Exercise
You need to find the value 42 in an unsorted array of n elements. Is this O(1) because arrays support O(1) indexing? Explain.
Show answer
No. Indexing is O(1) only when you know the position. Finding a value in unsorted data requires checking elements one by one, so the search is O(n). An array and a linked list cost the same here.