DSA — Linear Search
What is Linear Search?
Sequentially checks each element until the target is found or the list ends.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
Variations
# Find all occurrences
def find_all(arr, target):
indices = []
for i, val in enumerate(arr):
if val == target:
indices.append(i)
return indices
# Find first occurrence
def find_first(arr, target):
for i, val in enumerate(arr):
if val == target:
return i
return -1
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(1) |
| Average | O(n) |
| Worst | O(n) |
When to Use
- Small datasets
- Unsorted data
- Single search needed
Mini Practice
- Implement linear search
- Find all occurrences
- Search in a 2D array
- Compare with binary search
Up Next
Continue with Binary Search — efficient search algorithm.
Related Topics
Frequently Asked Questions about Linear Search
What is Linear Search in DSA?
Linear Search is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Linear Search?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Linear Search.
Why is Linear Search important in DSA?
Linear Search is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.