Linear Search Algorithm in DSA Go - Time & Space Complexity
We want to understand how the time taken by linear search changes as the list size grows.
How many steps does it take to find an item or decide it's not there?
Analyze the time complexity of the following code snippet.
func linearSearch(arr []int, target int) int {
for i, val := range arr {
if val == target {
return i
}
}
return -1
}
This code looks through each item in the list one by one to find the target value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the list one by one.
- How many times: Up to n times, where n is the number of items in the list.
As the list gets bigger, the number of checks grows roughly the same as the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows linearly with the number of items.
Time Complexity: O(n)
This means the time to find the item grows directly with the list size.
[X] Wrong: "Linear search always takes the same time no matter the list size."
[OK] Correct: The search time depends on where the target is or if it is missing, so bigger lists usually take more time.
Understanding linear search time helps you compare it with faster methods and shows you can analyze simple algorithms clearly.
"What if the list was sorted and we used binary search instead? How would the time complexity change?"