DSA — Searching Algorithms

Linear Search

Scan each element one by one until the target is found or the array ends. Works on any unsorted array.

— min read
O(n)Time
O(1)Space
WorksUnsorted
SimpleApproach
SequentialCheck
// LINEAR SEARCH
Enter target and press Search
How It Works
Python Code
Complexity
Quiz
Practice
01
Start Left
Begin from index 0.
i = 0
02
Compare
Check arr[i] == target.
if arr[i] == target: return i
03
Advance
Move right if not matching.
i += 1
04
Not Found
Return -1 if end reached.
return -1
python
def linear_search(arr, target):
    for i, val in enumerate(arr):
        if val == target:
            return i
    return -1
O(n)
Worst Case
Target at end or absent
O(1)
Best Case
Target is first element
O(n)
Average
~n/2 comparisons on average
Any
Array type
Unsorted, sorted, any data type
When is Linear Search preferred over Binary Search?
Progress 0 / 3 solved
3 problems · 1 PBC · 2 Startup
#004 Maximum Subarray Meta, Amazon PBC
#013 Equilibrium Index Zomato STARTUP
#018 Find Duplicates in Array Cogoport STARTUP