Search with a sentinel
Challenge · Write code · about 12 min
Return the index of the first cell of nums equal to target, or -1 if there is none, using a sentinel.
Append target to the end of nums first. The scan loop must then test only nums[i] != target, with no i < n check, because the sentinel always stops it. Remove the sentinel before you return, so nums is unchanged.
Example 1
Input:
[[7,3,9,1,8],9]
Output:
2
The scan stops at the real 9 before it reaches the sentinel.
Example 2
Input:
[[7,3,9,1,8],5]
Output:
-1
The scan reaches the sentinel at index 5 = n, so 5 is missing.
Constraints
- 0 ≤ nums.length ≤ 10,000
- -10,000 ≤ nums[i], target ≤ 10,000
- The loop condition compares values only
Learn the idea first: Linear search, a visual lesson.
More Linear search problems
- Index of target Warm-up
- Count occurrences Standard
- Last index of target Standard
- Trace a linear scan Standard