Sub topic 4
The Sentinel Trick for Linear Search
This chapter assumes you already know the plain linear search from earlier in the tutorial and can count its comparisons in the best, worst, and average case. You should also be comfortable with mutable arrays or lists, while loops, and try/finally (or the equivalent in your language). The sentinel trick is a small change to linear search. It does not change the Big-O cost, but it is a good exercise in reasoning about loop termination, and it has several edge cases that catch people out.
The Idea: Remove One Test from the Loop
A standard linear search does two tests on every iteration:
- A bounds test: is the index still inside the array (
i < n)? - A match test: does the current element equal the target (
a[i] == target)?
The bounds test exists only to stop the loop when the target is absent. If we could guarantee that the loop always finds the target, the bounds test would be unnecessary.
A sentinel is a value placed in the data so that the loop is guaranteed to stop. For linear search, the sentinel is the target itself, written into the last position of the array. The scan then needs only the match test, because it will hit the target no later than the last slot. After the loop ends, one extra check decides whether we found a real match or just the sentinel.
Counting the Saved Comparisons
Take an array of length n that does not contain the target, which is the worst case for both versions.
| Version | Bounds tests | Element comparisons | Post-loop checks | Total |
|---|---|---|---|---|
| Standard linear search | n + 1 | n | 0 | 2n + 1 |
| Sentinel linear search | 0 | n | 2 | n + 2 |
The sentinel version does about half as many tests. Both versions are still O(n), so the sentinel changes the constant factor only. Whether that constant matters depends on the language and hardware, which we come back to below.
A Python Implementation
def sentinel_search(items, target):
n = len(items)
if n == 0:
return -1
last = items[-1]
items[-1] = target # plant the sentinel
i = 0
try:
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 (target was the real last element)
print(sentinel_search(data, 5)) # -1
print(sentinel_search([], 5)) # -1
print(data) # [4, 2, 7, 1] (unchanged)Each part of this code has a job:
- Empty check. With
n == 0there is no slot for the sentinel. Writingitems[-1]would raiseIndexErrorin Python and corrupt memory in C. - Saving
last. The sentinel overwrites real data, so we keep a copy. try/finally. If anything inside the loop raises, the caller's list is still restored. The NaN case below shows how the loop can raise.- Post-loop check. If
i < n - 1, the loop stopped on a real element before the sentinel slot. Ifi == n - 1, the loop reached the sentinel, and the result is a real match only if the original last element was the target.
A Java Implementation
In Java and C the sentinel trick removes an explicit comparison from a tight loop, so it fits these languages better than Python.
public class SentinelSearch {
static int sentinelSearch(int[] a, int target) {
int n = a.length;
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;
}
public static void main(String[] args) {
int[] a = {4, 2, 7, 1};
System.out.println(sentinelSearch(a, 7)); // 2
System.out.println(sentinelSearch(a, 1)); // 3
System.out.println(sentinelSearch(a, 5)); // -1
System.out.println(sentinelSearch(new int[0], 5)); // -1
System.out.println(java.util.Arrays.toString(a)); // [4, 2, 7, 1]
}
}With int elements nothing inside the loop can throw, so this version needs no finally. If you adapt it to objects and equals, a user-defined equals could throw. In that case wrap the loop in try/finally the same way the Python version does.
Edge Cases and Failure Modes
The input must be writable
The sentinel trick temporarily changes the array. That rules it out in several situations:
- The data is immutable: a Python
tuple, astr, a JavaList.of(...), or a memory-mapped read-only file. - The function's contract promises not to touch its argument, and callers rely on that promise.
- The caller passed a view or slice that shares storage with something else.
A common workaround is to allocate the array with one spare slot at the end that holds no data. The sentinel goes there and no real element is ever overwritten. This is the classic textbook form. It only works when you control how the array is allocated.
Concurrency
While the search runs, the last slot holds the wrong value. Another thread reading the array at that moment sees corrupted data. Another thread writing to the array can overwrite the sentinel, and then the loop may run past the end. Sentinel search on shared data needs a lock held for the whole search, and the lock usually costs more than the comparison you saved.
Equality that is not reflexive
The whole trick assumes that target == target is true, so the loop must stop at the sentinel. Floating-point NaN breaks that assumption, because NaN != NaN is always true.
import math
def sentinel_search(items, target):
n = len(items)
if n == 0:
return -1
last = items[-1]
items[-1] = target
i = 0
try:
while items[i] != target:
i += 1
finally:
items[-1] = last
if i < n - 1 or last == target:
return i
return -1
data = [1.0, 2.0, 3.0]
try:
sentinel_search(data, math.nan)
except IndexError:
print("ran off the end") # ran off the end
print(data) # [1.0, 2.0, 3.0] (finally restored it)In Python the scan runs past the end and raises IndexError, and finally restores the list. In C the same loop reads past the end of the buffer, which is undefined behavior. Objects with a custom __eq__ or equals that is not reflexive cause the same problem. If NaN or similar values are possible, reject them before planting the sentinel, or use the standard loop.
Duplicates
The loop stops at the first match, so with duplicates the sentinel version returns the first occurrence, the same as standard linear search. The sentinel affects the result only when the loop reaches the last slot.
Does It Actually Run Faster?
The comparison count halves, but wall-clock time often does not. Several things reduce the gain:
| Environment | Why the gain shrinks |
|---|---|
| Python | Interpreter overhead per iteration is far larger than one integer comparison. A `for` loop with `enumerate` or the built-in `list.index` is usually faster than either hand-written `while` loop. |
| Java | The JIT compiler often removes bounds checks it can prove are safe, and the `i < n` test predicts well. |
| C/C++ with optimization | The `i < n` branch is almost always predicted correctly, and compilers may vectorize the standard loop. The sentinel loop's data-dependent exit can prevent vectorization. |
| Small embedded CPUs, no branch prediction | The trick can still save measurable time here. |
The idea is more useful as a way of thinking than as a micro-optimization. Sentinels show up elsewhere: the null terminator at the end of a C string, dummy head nodes in linked lists, and the infinity value added at the end of each half in some merge implementations. In each case one extra value placed at a boundary removes a special-case test from the main loop.
Summary of the Rules
- Plant the target in the last slot (or a spare slot), and save what was there.
- Loop on the match test alone.
- Restore the slot, using
finallyif anything in the loop can raise. - Return
iifi < n - 1or the saved value equals the target; otherwise return -1. - Handle the empty array before anything else.
- Do not use the trick on immutable, shared, or NaN-containing data.
Exercise
A colleague's sentinel search ends with return i if i < n - 1 else -1. Give an input on which it returns the wrong answer, and state the fix.
Show answer
Any array where the target appears only in the last position, for example [4, 2, 7, 1] with target 1. The loop stops at index 3, which is n - 1, so the code returns -1 even though 1 is present. The fix is to also check the saved original value: return i if i < n - 1 or last == target else -1.
Exercise
For an array of 1,000 elements that does not contain the target, how many tests do the standard and sentinel versions perform, using the counts in this chapter? Why might the sentinel version still not be faster in Python?
Show answer
Standard: 2n + 1 = 2,001 tests. Sentinel: n + 2 = 1,002 tests. In Python, each loop iteration spends most of its time on interpreter work such as bytecode dispatch, index lookup, and object comparison. Removing one cheap integer comparison per iteration changes little, and the built-in list.index, which is written in C, beats both hand-written loops.
Exercise
Why does the Python implementation use try/finally, and what concrete input makes the loop raise an exception?
Show answer
The sentinel temporarily overwrites the caller's last element, so the function must restore it on every exit path, including exceptions. Searching a list of floats for math.nan causes the problem: nan != nan is always true, so the loop never stops at the sentinel and raises IndexError when it runs past the end. Without finally, the caller's list would be left with NaN in its last slot.
Exercise
You need to search a tuple of user IDs that several threads read at the same time. Should you use sentinel search? Explain.
Show answer
No. A tuple is immutable, so you cannot plant the sentinel without copying it, and the copy costs O(n), which cancels any saving. Even with a mutable list shared between threads, other threads would see the sentinel in the last slot during the search, and concurrent writes could remove it and let the loop run past the end. Use a standard linear search, or tuple.index in a try block.