Searching · Easy

Linear search

Return the first index of target, or -1 if absent. Positions are counted from zero. If the target appears more than once, stop at its first occurrence.

Worked example

([4, 7, 7], 7) → 1

  1. At position 0, 4 does not match 7.
  2. At position 1, 7 matches. Return 1 without checking the other 7.

Python solution

def solve(nums, target):
    for index, num in enumerate(nums):
        if num == target:
            return index
    return -1

Scan from left to right and stop at the first match.

Time: O(n) · Space: O(1)

Practise in GymType