Sub topic 3
How Long Linear Search Takes
This chapter assumes you can read Python, know what a list and a zero-based index are, and have seen Big-O notation before. It builds on the linear_search function from the previous chapter and asks one question: how much work does that function do, and how does the answer change with the input?
Counting the Right Thing
Wall-clock time depends on the machine, the interpreter, and what else is running. To reason about an algorithm, we count a basic operation instead. For linear search, that operation is the comparison value == target. Every loop iteration does exactly one, and everything else in the loop (advancing the index, the enumerate bookkeeping) is a constant amount of extra work per iteration. If we know the number of comparisons, we know the running time up to a constant factor.
Here is the search from the previous chapter, modified to report how many comparisons it made:
def linear_search_count(items, target):
comparisons = 0
for i, value in enumerate(items):
comparisons += 1
if value == target:
return i, comparisons
return -1, comparisons
data = [4, 2, 7, 1, 9, 3]
print(linear_search_count(data, 4)) # (0, 1) found at the front
print(linear_search_count(data, 3)) # (5, 6) found at the back
print(linear_search_count(data, 8)) # (-1, 6) not presentThese three calls already show the three cases this chapter covers.
Best, Worst, and Average Case
For a list of length n:
- Best case: the target is at index 0. One comparison. This is constant time, O(1).
- Worst case: the target is at the last index, or it is not in the list at all. Both take
ncomparisons. This is O(n). - Average case: depends on where targets tend to be, which needs an assumption. The next section works it out.
If the target sits at index i, the search makes exactly i + 1 comparisons. If it is absent, the search makes n comparisons, because it has to check every element before it can say -1.
A successful search that finds the last element costs the same as a failed search. That is why the "not found" case gets so much attention. In many real workloads, such as checking whether a username is already taken, most searches fail, and every failure pays the full price.
Deriving the Average Case
The average case needs a model of which targets get searched for. The standard model has two parts:
- If the target is present, it is equally likely to be at any of the
npositions. - The target is present with probability
p.
Target present. Each position i (0-based) costs i + 1 comparisons and has probability 1/n. The expected cost is:
(1 + 2 + ... + n) / n = (n(n + 1) / 2) / n = (n + 1) / 2
On average, a successful search scans about half the list.
Target absent. The cost is always n.
Combined. The expected cost is:
p · (n + 1) / 2 + (1 − p) · n
| Scenario | p | Expected comparisons (n = 1000) |
|---|---|---|
| Always found | 1.0 | 500.5 |
| Found half the time | 0.5 | 750.25 |
| Never found | 0.0 | 1000 |
Every row is proportional to n. Constant factors such as 1/2 or 3/4 disappear in Big-O, so the average case is O(n) whatever p is. Searching a list twice as long takes about twice as long on average.
You can check the formula by experiment:
import random
def linear_search_count(items, target):
comparisons = 0
for i, value in enumerate(items):
comparisons += 1
if value == target:
return i, comparisons
return -1, comparisons
n = 1000
items = list(range(n))
random.shuffle(items)
# Exact: search for every element once.
total = sum(linear_search_count(items, x)[1] for x in items)
print(total / n) # 500.5, which is (n + 1) / 2
# Simulated: present with probability 0.5.
random.seed(42)
trials = 20000
total = 0
for _ in range(trials):
if random.random() < 0.5:
target = random.choice(items) # present
else:
target = -1 # absent
total += linear_search_count(items, target)[1]
print(round(total / trials, 1)) # close to 750.25The first result is exact because every position is searched exactly once. The second result is a random estimate, so it will land near 750 rather than exactly on 750.25.
Big-O, Big-Omega, and Big-Theta
People often mix up "best case" with "lower bound", so it helps to keep the terms separate.
- Big-O gives an upper bound on growth. Big-Omega (Ω) gives a lower bound. Big-Theta (Θ) means both bounds hold.
- Best case, worst case, and average case are each a separate function of
n. You can put any of the three notations on any of them.
For linear search:
| Case | Comparisons | Tight bound |
|---|---|---|
| Best | 1 | Θ(1) |
| Average (any fixed p) | p(n+1)/2 + (1−p)n | Θ(n) |
| Worst | n | Θ(n) |
When someone says "linear search is O(n)" with no qualifier, they mean the worst case, and that statement is correct. "Linear search is O(1)" is wrong, even though the best case is constant. A best case only tells you about inputs that happen to be lucky.
Space Complexity
Linear search uses an index and a loop variable no matter how long the list is, so its extra space is O(1). It does not copy the list, sort it, or build any auxiliary structure. This matters later, because the faster alternatives either need sorted data or need extra memory for an index such as a hash table.
Hidden Costs
The comparison count is the right model only when each comparison costs a constant amount. Two situations break that assumption.
Expensive comparisons. Comparing two strings of length m can take up to m character checks. Searching n strings costs O(n · m) in the worst case. Strings with long shared prefixes, such as file paths or URLs, are where this shows up.
Linear search inside a loop. Python's x in some_list and some_list.index(x) both do linear searches. They are easy to miss inside a loop:
def common_items(a, b):
# Each "x in b" scans b: O(len(a) * len(b)) overall.
return [x for x in a if x in b]
def common_items_fast(a, b):
# Build a set once: O(len(a) + len(b)) on average.
b_set = set(b)
return [x for x in a if x in b_set]
print(common_items([1, 2, 3, 4], [3, 4, 5])) # [3, 4]
print(common_items_fast([1, 2, 3, 4], [3, 4, 5])) # [3, 4]With 10,000 items in each list, the first version can make up to 100 million comparisons, and the second makes about 20,000 hash operations. Neither function looks slow when you read it. You only see the cost when you ask what each line does inside the loop.
Measuring Growth on a Real Machine
Counting comparisons is the model. Timing shows whether the model matches reality. Doubling n for an absent target should roughly double the time:
import timeit
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
return -1
for n in [10_000, 20_000, 40_000, 80_000]:
items = list(range(n))
t = timeit.timeit(lambda: linear_search(items, -1), number=200)
print(f"n={n:>6} time={t:.4f}s")The exact numbers depend on your machine. The ratio between consecutive rows should be close to 2. That ratio is what O(n) predicts, and you can use the same check on any function you suspect of hidden linear work.
Common Errors
- Quoting the best case as the running time. "It usually finds things at the start" is a claim about your data, not about the algorithm. State it as an assumption if you rely on it.
- Forgetting the absent case. An average that only covers successful searches gives (n+1)/2 and underestimates workloads where many searches fail.
- Treating n/2 as better than O(n). Halving the constant does not change how the cost grows. A list ten times longer still takes about ten times longer to search.
- Counting the wrong operation. If comparisons are not constant time, the comparison count understates the real cost.
Exercise
A list holds 2,000 unique items. Searches find the target 80% of the time, and when found the target is equally likely to be at any position. What is the expected number of comparisons per search?
Show answer
0.8 × (2000 + 1) / 2 + 0.2 × 2000 = 0.8 × 1000.5 + 400 = 800.4 + 400 = 1200.4 comparisons.
Exercise
A function loops over a list of k query strings and calls queries_list.index(q) on a list of n stored strings, each of length up to m. What is the worst-case running time, and why?
Show answer
O(k · n · m). Each of the k calls to index is a linear search that can compare against all n stored strings, and each string comparison can check up to m characters.
Exercise
A colleague says "linear search is Ω(1) and O(n), so it isn't really Θ of anything." What is wrong with this reasoning?
Show answer
It mixes up cases with bounds. Each case has its own tight bound: the best case is Θ(1) and the worst case is Θ(n). Θ applies to a specific case function, not to the algorithm as a whole. Read as a worst-case statement, linear search is Θ(n).