Linear search (also called sequential search) checks the elements one by one, from the first to the last, until it finds the target or runs out of elements. It needs no preparation, works on any sequence (sorted or not, array or linked list or stream) and is the baseline every faster search is measured against. Knowing exactly when this humble O(n) scan is the right tool is a surprisingly practical skill.
Think of it like
Finding a friend in a cinema queue
You walk along the queue and look at each face in turn. If your friend is near the front you find them quickly; if they are at the back, or not in the queue at all, you have to look at everyone. Nothing about the queue's order helps you, but nothing needs to be prepared either: you just start walking.
How it works
Keep an index i starting at 0. At each step compare a[i] with the target. On a match, return i; otherwise move to i + 1. If i reaches n without a match, the target is absent and the function returns a sentinel value such as -1.
- 1
Start at the front
Set
i = 0. Nothing about the data needs to be sorted or indexed beforehand. - 2
Compare
Check whether
a[i] == target. This is the only operation the algorithm needs: an equality test. - 3
Stop on a match
If it matches, return
iimmediately. The first occurrence wins. - 4
Advance
Otherwise increment
iand repeat whilei < n. - 5
Report absence
If the loop finishes, every element has been checked, so return
-1.
Complexity and expected comparisons
The best case is 1 comparison (the target is first). The worst case is n comparisons, which happens both when the target is last and when it is absent. The interesting question is the average case, which depends on where the target tends to be.
If the target is present only with probability p, a miss still costs n comparisons, so the expectation becomes p·(n + 1)/2 + (1 − p)·n. For a search that usually fails (for example, checking a blocklist that rarely matches), the expected cost is close to the full n.
| Scenario | Comparisons | Order |
|---|---|---|
| Target at index 0 | 1 | O(1) |
| Target at a uniformly random position | (n + 1)/2 on average | O(n) |
| Target at the last index | n | O(n) |
| Target absent | n | O(n) |
The sentinel optimization
The plain loop performs two tests per iteration: the bounds check i < n and the equality check a[i] == target. A sentinel removes the bounds check. Overwrite the last element with the target, so the scan is guaranteed to stop, then restore the original value and figure out whether you hit a real match or the sentinel.
Plain loop
while i < n and a[i] != target: i += 1- Two comparisons per element
- Read-only: safe on shared or immutable data
Sentinel loop
- Save
last = a[n-1], then seta[n-1] = target while a[i] != target: i += 1(one comparison per element)- Restore
a[n-1]; it is a real match ifi < n-1orlast == target
When linear search is the right choice
Linear search wins
- Unsorted data and only one or a few queries
- Tiny arrays where constant factors dominate
- Linked lists, streams and iterators (no random access)
- Data that changes constantly, so keeping it sorted is costly
- Arbitrary predicates such as "first user older than 30 in Paris"
Something else wins
- Many queries on static data: sort once, then use Binary Search
- Many membership queries: build a hash set (Hash Tables) for O(1) lookups
- Range queries or ordered iteration: use a balanced tree (Binary Search Trees)
With k queries on n unsorted items, linear search costs about k·n. Sorting first costs n log₂ n once, then log₂ n per query. Sorting pays off once k grows past roughly log₂ n queries: for a million elements that is only about 20 searches.
Linear search
1,000,000
worst-case comparisons, n = 10⁶
Binary search
20
after an O(n log n) sort
Hash set lookup
~1
after an O(n) build, expected
Linked lists have no shortcut
On a Linked Lists structure you cannot jump to the middle element, so even a sorted linked list cannot be binary searched efficiently: reaching the midpoint already costs O(n). Linear search is the natural (and optimal) way to search a list, and the same holds for data arriving as a stream, where each element is seen once and cannot be revisited.
Useful variations
Finding all occurrences
Do not stop at the first match: scan the whole array and collect every index where a[i] == target. This always costs exactly n comparisons and returns a list of size 0 to n. Counting occurrences is the same scan with a counter instead of a list.
Last occurrence
Scan from the back (i = n - 1 down to 0) and return the first match you meet. This is what str.rfind and lastIndexOf do.
Minimum and maximum
Finding the minimum is a linear search where the "target" keeps changing: compare each element with the best seen so far. It takes exactly n − 1 comparisons, and no algorithm can do better, since every element except the winner must lose at least one comparison. Finding the min and the max separately costs 2n − 2 comparisons, but processing elements in pairs does better: compare the two elements of a pair with each other, then only the smaller against the current min and the larger against the current max.
Self-organizing lists
When some keys are searched much more often than others, a list can reorder itself to make future searches cheaper. Move-to-front moves each found element to index 0; transpose swaps it one step forward. Frequently requested items drift to the front, so their searches become short. The same idea powers move-to-front encoding in compressors such as bzip2.
Linear search in standard libraries
| Language | Functions | Returns |
|---|---|---|
| Python | x in a, a.index(x), a.count(x), min(a), max(a) | bool, index (raises ValueError if absent), count, value |
| JavaScript / TypeScript | a.includes(x), a.indexOf(x), a.find(fn), a.findIndex(fn), a.findLast(fn) | bool, index or -1, element or undefined, index or -1 |
| Java | list.contains(x), list.indexOf(x), list.lastIndexOf(x), Collections.min/max | bool, index or -1, value |
| C++ | std::find, std::find_if, std::count, std::min_element, std::minmax_element | iterator (end if absent), count, iterator(s) |
std::minmax_element uses the pairwise trick, so it needs only about 3n/2 comparisons.Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Best | O(1) | O(1) | Target is the first element |
| Average | O(n) | O(1) | About (n + 1)/2 comparisons when present |
| Worst | O(n) | O(1) | Target is last or absent: n comparisons |
| All occurrences | O(n) | O(k) | k = number of matches returned |
| Min and max together | O(n) | O(1) | ⌈3n/2⌉ − 2 comparisons with the pairwise trick |
Works on unsorted data and on any sequence that can be iterated, including linked lists and streams.
Implementation
Returns the index of the first occurrence, or -1 when the target is absent.
def linear_search(a: list[int], target: int) -> int:
for i, x in enumerate(a):
if x == target:
return i # first occurrence
return -1 # checked all n elementsKey takeaways
- Linear search checks elements one by one: O(1) best case, O(n) average and worst case, O(1) extra space.
- A present target at a uniformly random position costs (n + 1)/2 comparisons on average; a miss always costs n.
- It is the right tool for unsorted data with few queries, tiny arrays, linked lists and streams.
- For many queries, sort once and binary search, or build a hash set: the break-even point is only about log₂ n queries.
- Variants (all occurrences, last occurrence, min/max with ⌈3n/2⌉ − 2 comparisons) are all single linear passes.
Common pitfalls
- Hiding a linear search inside a loop (
x in list,includes,contains), which turns an O(n) algorithm into O(n²). - Sorting the data just to run a single search: O(n log n) to save an O(n) scan is a net loss.
- Forgetting to restore the overwritten element in the sentinel version, or to check whether the match was the sentinel itself.
- Returning
0orfalsefor "not found" when0is also a valid index; use-1,Noneor an optional type.
Interview tips
- State the lower bound: on unsorted data, any search must examine every element in the worst case, so O(n) is optimal.
- Ask how many queries will be made before choosing between a scan, sorting plus binary search, or a hash set.
- If asked for min and max together, mention the pairwise trick and its ⌈3n/2⌉ − 2 comparisons.
Real-world applications
- Searching small or unsorted collections, such as a handful of configuration entries.
- Scanning linked lists, log files and network streams where random access is impossible.
- Filtering records by an arbitrary predicate (
WHEREclauses without an index perform a full table scan). - Finding extremes: the minimum, the maximum, or the first element satisfying a condition.
Practice problems
Test yourself
The target is present and equally likely to be at any of the n positions. How many comparisons does linear search make on average?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.