← Back to DSA
🔍
Searching
Linear Search
Scans every element from the start until the target is found or the end is reached. Works on any unsorted collection.
Complexity
Time (Best)
O(1)
Time (Avg)
O(n)
Time (Worst)
O(n)
Space
O(1)
Key Points
- ›Works on unsorted data — no preprocessing required
- ›O(1) space — no additional memory needed
- ›Simple and reliable but slow for large datasets
- ›Best when the list is small or you expect the element near the front
- ›Necessary when the collection cannot be sorted
Code Examples
Swift
func linearSearch<T: Equatable>(_ arr: [T], target: T) -> Int? {
for (index, element) in arr.enumerated() {
if element == target { return index }
}
return nil
}
let nums = [4, 2, 7, 1, 9, 3, 5]
if let idx = linearSearch(nums, target: 7) {
print("Found at index \(idx)") // Found at index 2
} else {
print("Not found")
}Practice Problems
Find the Index of the First Occurrence in a String
EasyLeetCode ↗
Search in a Binary Search Tree
EasyLeetCode ↗