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
- Start at the first element (index 0) of the array.
- Compare the current element with the target value.
- If they match, return the current index (target found).
- If they don't match, move to the next element.
- 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?