Home
DSA Visualizer
Searching
Linear Search
Linear Search Visualization
Sequentially checks each element of the list until a match is found or the whole list has been searched. Step through it in the interactive Linear Search visualization below.
Intuition
Imagine you are looking for a specific book on a messy bookshelf where the books are not organized. To find it, you have to look at the first book, then the second, then the third, and so on, until you find the one you want or reach the end of the shelf. This checking "one by one" is exactly how Linear Search works.
Concept
Linear Search is the simplest search algorithm. It checks every element in the list sequentially, starting from the first element, until a match is found or the entire list has been traversed. It runs in O(n) time complexity.
How Linear Search Works
- Start at the first element (index 0).
- Compare the current element with the target value.
- If they match, return the current index (Success!).
- If they don't match, move to the next element.
- Repeat until you find the target or run out of elements.
- If you reach the end without finding it, return -1 (Not Found).
Linear Search Visualization, Step by Step
- Start at the beginning: Point your finger at the first item.
- Check it: Is this the item you are looking for?
- Yes? You're done! Stop searching.
- No? Move your finger to the next item.
- Keep going: Repeat this for every single item in the line.
- Give up? If you reach the end and haven't found it, it's not there.
Trace: Search 30 in [10, 50, 30, 70]
Check Index 0
Compare arr[0] (10) with Target (30).
10 != 30. Continue.
Check Index 1
Compare arr[1] (50) with Target (30).
50 != 30. Continue.
Check Index 2
Compare arr[2] (30) with Target (30).
30 == 30. Found!
Found
Return index 2.
When to Use
- Unsorted Data: It is the only way to search if the list is not sorted.
- Small Datasets: For very small lists, it's fast enough and easy to implement.
- Linked Lists: You cannot jump to the middle of a linked list, so you must use linear search.
When NOT to Use
- Large Sorted Datasets: Binary Search is much faster (O(log n) vs O(n)).
- Frequent Searches: If you search the same large list many times, it's better to sort it first or use a Hash Map.
How to Identify
You will rarely be asked to implement "Linear Search" explicitly. However, iterating through an array to find an element, find the max/min, or count occurrences are all variations of Linear Search. Look for keywords like "Unsorted", "Find first occurrence", or searching in a Linked List.
Practice it on interview problems
LeetCode problems solved with the Binary Search pattern, each with a step-by-step visualizer:
Applying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
