Sub topic 4
The Sentinel Trick for Linear Search
This chapter assumes you already know the basic linear search from earlier in the tutorial, can read simple Python and C, and know that linear search runs in O(n) time. The sentinel trick leaves the Big-O cost unchanged. It reduces the work done inside the loop on each step.
Where the Extra Work Hides
A standard linear search makes two checks on every iteration:
- Is the index still inside the list? (
i < n) - Does the current element equal the target? (
a[i] == target)
A for loop in Python hides the first check, but it still runs. The bounds check is necessary only because the target might be missing. Without it, the loop would read past the end of the array.
A sentinel is a guard value placed so the loop is certain to stop. If you write the target into the last slot, the equality check will always succeed by the end of the array. That makes the bounds check redundant, so you can remove it.
| Version | Checks per iteration | Checks after the loop |
|---|---|---|
| Standard linear search | 2 (bounds, equality) | 0 |
| Sentinel linear search | 1 (equality) | 1 or 2 (was it the real element?) |
How It Works
The check after the loop matters. If the loop stopped at the last index, you can't yet tell whether it found the planted sentinel or a real match. The saved original value settles it.
Implementation in Python
def sentinel_search(items, target):
n = len(items)
if n == 0:
return -1
last = items[-1]
items[-1] = target
try:
i = 0
while items[i] != target:
i += 1
finally:
items[-1] = last # always restore the caller's data
if i < n - 1 or last == target:
return i
return -1
data = [4, 2, 7, 1]
print(sentinel_search(data, 7)) # 2
print(sentinel_search(data, 1)) # 3
print(sentinel_search(data, 5)) # -1
print(data) # [4, 2, 7, 1]The try/finally block puts the original value back even if a comparison raises an exception. In Python the speed gain is small, because interpreter overhead is much larger than the cost of one comparison. The trick helps more in compiled languages.
Implementation in C
#include <stdio.h>
int sentinel_search(int *a, int n, int target) {
if (n == 0) return -1;
int last = a[n - 1];
a[n - 1] = target;
int i = 0;
while (a[i] != target) {
i++;
}
a[n - 1] = last;
if (i < n - 1 || last == target) return i;
return -1;
}
int main(void) {
int a[] = {4, 2, 7, 1};
printf("%d\n", sentinel_search(a, 4, 7)); /* 2 */
printf("%d\n", sentinel_search(a, 4, 5)); /* -1 */
return 0;
}Common Errors and Limits
- Forgetting to restore the last element. The caller's data is silently corrupted.
- Skipping the final check. Every missing target would be reported at index
n - 1. - Ignoring the empty list. Writing to
a[-1]ora[n - 1]whenn == 0fails, or in C, writes outside the array. - Read-only or shared data. The trick needs write access. It doesn't work on tuples, strings, or constant arrays, and it isn't safe when other threads read the array at the same time.
- Unusual equality. Values such as floating-point NaN never equal themselves, so the loop never stops and runs past the end.
Exercise
A colleague removes the line if i < n - 1 or last == target and simply returns i whenever i < n. For the list [4, 2, 7, 1], what does searching for 5 return, and why is that wrong?
Show answer
It returns 3. The planted sentinel at index 3 stops the loop, so the colleague's version reports the target at the last index even though 5 is not in the list. The final check compares the saved original value (1) with the target, sees they differ, and correctly returns -1.
Exercise
Why does the sentinel version still run in O(n) time in the worst case?
Show answer
Removing the bounds check lowers the work per iteration, but when the target is missing or near the end, the loop still visits up to n elements. Only the constant factor improves.