Linear Search
Pattern: Traversal and in-place tricks
Look at each element in order and return the index of the first one equal to the target, or -1 if none is.
The problem
You are given an array of between 1 and 100,000 whole numbers and a number target. Return the index of the first
element equal to target, or -1 if there is none. For example, in [4, 7, 1, 7] the target 7 is first found at index 1.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name linearSearch, the "first match" rule and the limits are this guide's own.
Think first
- The array is not sorted. Can you skip any element?
- If the target appears twice, which index should you return, and how does that decide when to stop?
- What do you return when the loop finishes without a match?
Hints
Brute force, and why it fails
This is already the simplest method, and for an unsorted array it is the best possible: any element you skip could have been the target. When the array is sorted, binary search finds a value in O(log n), which comes later in this course.
The key insight
Scan in order and stop at the first match. Stopping early means the first index is returned, and saves time when the target is near the front.
Dry run
| target | 7 |
|---|
nums = [4, 7, 1, 7] and target = 7. Start at index 0.
The plan
for i from 0 to n - 1:
if nums[i] == target:
return i # the first match
return -1 # checked everything, no match
Complexity
- Time
O(n)- Space
O(1)
In the worst case (target missing or last) every element is checked once.
Edge cases
- Target missing: -1.
- Target at index 0: one comparison.
- Repeated target: the first index is returned.
I've built my logic, show the code
Java
class Solution {
public int linearSearch(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
return i; // the first match
}
}
return -1;
}
}C++
class Solution {
public:
int linearSearch(vector<int>& nums, int target) {
for (int i = 0; i < static_cast<int>(nums.size()); i++) {
if (nums[i] == target) {
return i; // the first match
}
}
return -1;
}
};Python
class Solution:
def linearSearch(self, nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i # the first match
return -1Common mistakes
- Returning -1 inside the loop as soon as one element does not match.
- Returning the last match by continuing the loop and overwriting the answer.
- Returning the value instead of its index.