Linear Search
Given an array of integers and a target value, return the index of the first position whose value equals the target by scanning the array from left to right.…
Given an array of integers and a target value, return the index of the first position whose value equals the target by scanning the array from left to right. If the target appears more than once, return the index of its first occurrence. If the target never appears — including when the array is empty — return `-1`.
- `0 <= arr.length <= 10^4` - `-10^9 <= arr[i] <= 10^9` - `-10^9 <= target <= 10^9` - Return the index of the first matching element when duplicates exist. - Return `-1` when the target does not appear, including for an empty array.
Example 1: input arr = [4, 2, 7, 1, 9], target = 7; output 2. Scanning left to right, arr[2] = 7 is the first element equal to the target.
Example 2: input arr = [5, 3, 8], target = 5; output 0. The very first element arr[0] = 5 matches, so the scan returns immediately.
Example 3: input arr = [1, 2, 3], target = 6; output -1. No element equals 6, so after scanning every position the function returns -1.
Category: Sorting & Searching. Topic: sorting-searching. Difficulty: Easy. Patterns: linear-scan.