Last Updated: June 7, 2026
Find where a value lives inside an array. Report the position of the first element that matches the target, or -1 if nothing matches.
The word "first" shapes the solution. When the target shows up more than once, only the earliest position counts. Scanning left to right and stopping at the first match handles this automatically, since you reach the smaller index before any later one.
The array carries no ordering guarantee, so you cannot skip ahead or jump to a midpoint the way a sorted search would. Every element is a candidate until you have looked at it. An empty array has nothing to check, and the answer there is -1.
-1 sentinel for "not found" → A valid index is always 0 or greater, so -1 is a safe signal that the target never appeared. Return it only after the entire array has been scanned.Look at each element in turn and ask whether it equals the target. The first time the answer is yes, you have found the earliest position, so stop and return that index.
Returning on the first match gives the "first occurrence" behavior directly. Stopping early also saves work when the target appears near the front. If the loop runs to the end without a match, the target is not in the array, and -1 is the result.
i from 0 to the last position.nums[i] equals target, return i.-1.Input:
Start at index 0. nums[0] is 5, which is not 8, so move on. At index 1, nums[1] is 3, still not 8. At index 2, nums[2] is 8, which matches the target, so return 2 right away. The element at index 3 is never examined because the scan already found its answer.