Linear search
Unsorted data, small lists, or a one-off lookup.
Medium interview relevanceRoadmap: Beginner
| Time | O(n); O(1) if the target is first |
|---|---|
| Space | O(1) |
Why it costs this much
In the worst case it checks every item exactly once.
Code
def linear_search(items, target):
for i, x in enumerate(items): # up to n checks
if x == target:
return i # best case: first item, O(1)
return -1Common pitfalls
Repeating a linear search inside a loop makes O(n²). Build a set or dict first so each lookup is expected O(1).
Operation by operation
| Operation | Best | Average | Worst | Space |
|---|---|---|---|---|
| Linear search | O(1) if first | O(n) | O(n) | O(1) |
Linear search. Target equally likely to be anywhere, or absent. Works on unsorted data and any sequence, including linked lists.