Master Linear Search - O(n) Algorithm
Learn sequential search with step-by-step visualizations. Watch the pointer move through each element. Understand O(n) complexity and best/worst cases.
Linear Search Visualization
Enter array values to search
Use sample data or custom input
Array Input & Controls
Code Implementation
def linear_search(arr, target):
"""
Linear Search - Find first occurrence of target
Time: O(n) worst case, O(1) best case
Space: O(1) - no extra storage
"""
for i in range(len(arr)):
if arr[i] == target:
return i # Found at index i
return -1 # Not found
def linear_search_all(arr, target):
"""
Find all occurrences of target in array
Time: O(n) - must check all elements
Space: O(k) where k = number of matches
"""
indices = []
for i in range(len(arr)):
if arr[i] == target:
indices.append(i)
return indices
def linear_search_last(arr, target):
"""
Find last occurrence of target
Time: O(n) - must scan entire array
Space: O(1)
"""
last_index = -1
for i in range(len(arr)):
if arr[i] == target:
last_index = i
return last_index
# Usage examples
arr = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(arr, 22)) # Output: 4
print(linear_search(arr, 99)) # Output: -1 (not found)
# Find all occurrences
arr2 = [5, 2, 8, 2, 9, 2]
print(linear_search_all(arr2, 2)) # Output: [1, 3, 5]
# Find last occurrence
print(linear_search_last(arr2, 2)) # Output: 5Big O Complexity
Linear time - sequential search
Constant space - no extra storage
Complexity Cases
Target found at first position
Target in middle - n/2 comparisons
Target at end or not found - n comparisons
Properties
Works on: Unsorted or sorted arrays
In-place: Yes - O(1) extra space
Early exit: Yes - stops when found
Did You Know?
Simplest searching algorithm - checks each element sequentially
Only search that works on unsorted data without preprocessing
Best for small arrays (n < 100) or one-time searches
For sorted data, binary search (O(log n)) is much faster
When to Use Linear Search
Simple and effective for small datasets and unsorted data. Perfect for learning search fundamentals.
Small Arrays
For datasets with n < 100 elements, linear search is fast enough. Simple implementation outweighs optimization.
Unsorted Data
Only algorithm that works on unsorted data without O(n log n) sorting cost. Perfect for dynamic lists.
One-time Lookups
When you only search once, building an index or hash table isn't worth the overhead. Just scan the array.
Learning Tool
Perfect first algorithm for beginners. Teaches fundamental concepts like iteration and comparison.
Linked Lists
Binary search requires random access. For linked lists, linear search is often the only option.
Find All Matches
When you need to find all occurrences of a value, linear search scans the entire array efficiently.
When NOT to Use Linear Search
Large datasets: O(n) becomes slow. For sorted data, use binary search O(log n).
Repeated searches: Build a hash table for O(1) lookups instead of O(n) every time.
Sorted arrays: Binary search is exponentially faster - O(log n) vs O(n).
Performance critical: For millions of elements, consider indexed data structures or databases.
Free Linear Search Algorithm Tutorial: Learn Sequential Search with Interactive Visualization
Master linear search algorithm with step-by-step visualization. Understand O(n) time complexity, best case O(1), and when to use sequential search for unsorted data. Perfect for beginners learning algorithms and technical interview preparation.
What Is Linear Search Algorithm?
Linear search (also called sequential search) is the simplest searching algorithm that checks each element in an array one-by-one until the target is found. It's the only search algorithm that works on unsorted data without preprocessing, making it essential for dynamic lists according to GeeksforGeeks Algorithm Guide.
Linear search has O(n) time complexity in worst and average cases, but achieves O(1) best case when the target is at the first position. While slower than binary search O(log n) for sorted arrays, linear search requires no preprocessing and handles unsorted data—making it perfect for small datasets (n < 100), one-time searches, and linked lists where random access isn't available.
Why Learn Linear Search Algorithm:
Foundation for Algorithm Learning
- • Simplest algorithm: Perfect first search algorithm for beginners
- • Easy to understand: Intuitive sequential scanning pattern
- • Interview essential: Asked in 70% of junior dev interviews
- • Building block: Used in complex algorithms like insertion sort
Practical Applications
- • Unsorted data: Only option when data isn't sorted
- • Small datasets: Faster than binary search for n < 100
- • Linked lists: No random access needed
- • Real-time data: Works with constantly changing arrays
Linear Search Examples
Array: [42, 17, 8, 23]
Target: 42 Found at index 0, only 1 comparisonArray: [17, 8, 23, 42]
Target: 42 Found at last index, n comparisonsHow to Visualize Linear Search in 3 Steps
💡 Pro Tip: Learning Time Complexity
Use our interactive tool to test best, average, and worst cases. Watch how comparisons increase linearly with array size—this visual understanding of O(n) complexity is crucial for technical interviews at companies like Google, Amazon, and Microsoft.
Linear Search Time Complexity Analysis
Target found at index 0 (first position). Only 1 comparison needed regardless of array size. This is the fastest possible search but occurs in only 1/n probability. Example: searching for 42 in [42, 17, 8] immediately succeeds.
Target found in middle of array on average. Requires n/2 comparisons (still O(n) in Big-O notation). For array size 1000, expect ~500 comparisons. Most common scenario in real-world searches.
Target at last position or not in array. Must check all n elements. For 10,000 element array, requires 10,000 comparisons. This is why binary search O(log n) is preferred for sorted large datasets according to Khan Academy.
Linear search uses no extra memory beyond a few variables (loop counter, current value). In-place searching makes it memory-efficient for embedded systems and resource-constrained environments.
7 Real-World Linear Search Applications
1. Searching Unsorted Arrays
Only option for unsorted data. Unlike binary search which requires sorted arrays, linear search works on any data order. Essential for dynamic lists where maintaining sort order is expensive (e.g., real-time logs, user input).
2. Small Dataset Search (n < 100)
For small arrays, linear search is faster than binary search due to no preprocessing overhead. Comparing 50 elements takes microseconds—sorting first would be slower. Common in dropdown menus, settings panels, config files.
3. Linked List Traversal
Linked lists don't support random access (O(n) to reach middle), making binary search inefficient. Linear search is the natural choice for linked data structures where you traverse node-by-node anyway. Learn more with our Linked List Tutorial.
4. Finding All Occurrences
When you need every index where a value appears (e.g., finding all duplicates), linear search must scan the entire array anyway—O(n) is unavoidable. Used in data analysis, duplicate detection, pattern matching.
5. One-Time Search Operations
For single searches, avoiding preprocessing saves time. No indexing or sorting needed—just search. Common in command-line tools, quick scripts, data validation where you search once and discard the array.
6. Insertion Sort Inner Loop
Building block in sorting algorithms. Insertion sort uses linear search to find insertion position for each element. Understanding linear search is essential for learning advanced algorithms. See our Insertion Sort Guide.
7. Educational Purpose and Interviews
70% of coding interviews include linear search questions as warm-up or complexity analysis exercises. Perfect for teaching algorithm basics, Big-O notation, and comparison with binary search for understanding trade-offs.
Linear Search vs Binary Search: When to Use Each
| Criterion | Linear Search | Binary Search |
|---|---|---|
| Time Complexity | O(n) - Linear | O(log n) - Logarithmic ⚡ |
| Data Requirement | Any order (sorted/unsorted) ✓ | Must be sorted |
| Preprocessing | None required ✓ | Sorting: O(n log n) |
| Best for Small Data | n < 100 ✓ | n > 1000 |
| Linked Lists | Perfect ✓ | Inefficient (no random access) |
| Implementation | 5 lines of code ✓ | Recursive/iterative logic |
🎯 Decision Rule:
Use linear search for unsorted data, small arrays (n < 100), linked lists, or one-time searches. Use binary search for large sorted arrays (n > 1000) with repeated searches. For frequently searched data, use hash tables O(1) instead.
Linear Search Code Examples (5 Languages)
See our interactive tool above for complete implementations in Python, JavaScript, Go, Java, and C++ with detailed comments. All examples include time complexity analysis and best practices for production code.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Found at index i
return -1 # Not found
# Time: O(n), Space: O(1)5 Common Linear Search Mistakes to Avoid
1. Using Linear Search on Large Sorted Arrays
For sorted arrays with n > 1000, binary search is 1000x faster. Linear search on 1 million elements: 1M comparisons. Binary search: only 20 comparisons. Always use binary search for sorted large data.
2. Not Stopping Early (Find First)
Common bug: continuing loop after finding target. Use early return or break statement when first occurrence is found to avoid wasting comparisons. Best case O(1) only works with early exit.
3. Forgetting Array Bounds
Off-by-one errors cause crashes or missed elements. Loop should be i < length, not i <= length. Test with empty arrays and single elements to catch boundary bugs.
4. Ignoring Null/Empty Arrays
Always check if array is null or empty before searching. Return -1 or throw appropriate error. Production code must handle edge cases gracefully for robustness.
5. Confusing Linear Search with Binary Search
Interview mistake: implementing binary search when asked for linear. Linear = sequential left-to-right, no jumping. Binary = divide and conquer with mid-point checks. Know the difference for technical interviews.
Linear Search Algorithm FAQs
What is linear search algorithm in simple terms?
Linear search is a method to find a target value in an array by checking each element one-by-one from start to finish. Think of it like searching for a name in an unsorted phone book—you scan line-by-line until you find it. Time complexity: O(n) worst case, O(1) best case.
When should I use linear search instead of binary search?
Use linear search when: (1) data is unsorted (binary search requires sorted data), (2) array is small (n < 100), (3) searching a linked list, (4) finding all occurrences, or (5) one-time search where sorting overhead isn't worth it. For large sorted arrays, binary search is exponentially faster.
Why is linear search O(n) time complexity?
In worst case, you must check all n elements (target at end or not present). Each comparison is O(1), and you potentially do n comparisons: O(1) × n = O(n). As array doubles, search time doubles—this is linear growth. Best case O(1) when target is first element.
Can linear search work on linked lists?
Yes! Linear search is perfect for linked lists because it only needs sequential access. Binary search requires random access (jumping to middle), which linked lists don't support efficiently. Linear search traverses nodes one-by-one naturally. Learn more with our Linked List Tutorial.
How do I find all occurrences with linear search?
Instead of returning at first match, continue scanning and store all matching indices in an array. Space complexity becomes O(k) where k = number of matches. Our tool has "Find All" mode that demonstrates this—try it above!
Is linear search used in real applications?
Yes! Common in: (1) searching small config arrays, (2) filtering unsorted user input, (3) finding elements in linked lists, (4) insertion sort's inner loop, (5) one-time searches in scripts. Also essential for learning algorithms and technical interviews.
Advanced Linear Search Techniques
Sentinel Linear Search
Optimization: Add target to array end as "sentinel" to eliminate boundary check in loop. Reduces comparisons by ~50% in average case. Useful for performance-critical code with small arrays.
Transposition Heuristic
For repeated searches, move found element one position forward each time. Frequently accessed items migrate toward front, improving average case for non-uniform access patterns.
Move-to-Front Optimization
After finding element, move it to index 0. Next search for same element is O(1). Self-organizing list strategy for cache-like behavior with frequently accessed items.
Parallel Linear Search
Split array into chunks and search multiple segments concurrently using threads. Can achieve speedups on multi-core CPUs for very large arrays (n > 100,000).
Jump Search Hybrid
For sorted arrays, jump by √n steps then linear search in block. Better than pure linear O(n), worse than binary O(log n), but simpler than binary for some cases.
Predictive Linear Search
Track search history and start from last found position for sequential data. Useful in time-series or sorted-ish data where next target is likely nearby.
Related Search Algorithms & Data Structures
Master searching and sorting with our complete algorithm tutorials:
Ready to Master Linear Search?
Use our free interactive visualizer to understand O(n) complexity, test best/worst cases, and prepare for coding interviews. Perfect for beginners learning algorithms—no signup required, works in browser.
Used by 50,000+ students learning algorithms and data structures