Linear Search, explained step by step

Linear Search (also known as Sequential Search) is the most basic and intuitive method for finding a target value within a list. It simply checks every single element of the list, one by one, starting from the very first element and moving sequentially until a match is found or until all elements have been checked. It works perfectly on both sorted and unsorted data.

Intuition: Looking for your keys by checking every room in the house, one by one, until you find them.

How it works

  1. Start at the first element (index 0) of the array.
  2. Compare the current element with the target value.
  3. If they match, return the current index (target found).
  4. If they don't match, move to the next element.
  5. If the end of the array is reached, return -1 (target not found).

Complexity

  • Best: O(1)
  • Average: O(n)
  • Worst: O(n)
  • Space: O(1)
  • Stable: yes

When to use it

Unsorted arrays, small datasets, or when you need to find all occurrences.

Interview questions

  • When would you use Linear Search over Binary Search?
  • What is the average case comparisons for Linear Search?

Compare Linear Search

Open Linear Search in the visualiser