AlgoMaster Logo

Linear Search for a Target

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

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.

Key Constraints:

  • Array is not sorted → You cannot use binary search or assume any element tells you where the target sits. Each position has to be examined directly.
  • -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.
  • First occurrence on duplicates → When the target repeats, the smallest matching index is the answer. Returning the moment you find a match guarantees this, since the scan reaches lower indices first.

Approach 1: Linear Scan

Intuition

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.

Algorithm

  1. Loop over the array with an index i from 0 to the last position.
  2. If nums[i] equals target, return i.
  3. If the loop finishes without returning, return -1.

Example Walkthrough

Input:

0
5
1
3
2
8
3
1
nums
8
target

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.

2
result

Code