Linear search

Find the first shelf position with the requested label. Use zero-based indexing and -1 for a missing label.

Examples

Example 1

Input
[8, 4, 3, 4], target = 4
Expected output
1

Example 2

Input
[8, 4, 3, 4], target = 9
Expected output
-1

Hints and solution

Hint 1

Do not continue past a match.

Reveal worked answer

Compare in order and return the current position exactly when a match occurs. The second reading of 4 is skipped because index 1 already matched.

Back to the lesson