beginnersearching

Linear Search

Linear Search

Linear search (or sequential search) is the most straightforward way to find an element in a collection. It checks every element from start to end, one at a time. No sorting required, no data structure assumptions — it works on any list.

How It Works

  1. Start at the first element
  2. Compare the current element to the target
  3. If it matches, return the position
  4. If not, move to the next element
  5. If you reach the end without finding it, the target isn't in the array

Code Snippets

Find First Occurrence

def linear_search(elements: list[int], target: int) -> int:
    """Search for target by checking each element sequentially.
    Returns the index if found, -1 otherwise."""
    for position in range(len(elements)):
        if elements[position] == target:
            return position
    return -1

Find All Occurrences

def linear_search_all(elements: list[int], target: int) -> list[int]:
    """Find ALL positions where target appears."""
    found_positions = []
    for position in range(len(elements)):
        if elements[position] == target:
            found_positions.append(position)
    return found_positions

Time Complexity

  • Best case: O(1) — target is the first element
  • Worst case: O(n) — target is the last element or not present
  • Average case: O(n/2) which simplifies to O(n)
  • The array is unsorted (binary search requires sorting)
  • The array is small (n < 20, where the overhead of sorting isn't worth it)
  • You only search once (sorting + binary search is O(n log n + log n), worse than O(n) for a single query)
  • The data structure doesn't support random access (linked lists)

When to Upgrade

If you search the same collection many times, sort it once and use binary search. The upfront O(n log n) sort cost is amortized over many O(log n) searches, beating repeated O(n) linear scans.