Before we tackle fancier array problems, let's master the most fundamental operation: searching for something in an array.
Imagine you're at a huge concert looking for your friend. There's no VIP map, no assigned seats — just a sea of faces. What do you do? You start from one end and check each person one by one. That's linear search in a nutshell. 🎤👀
How it works:
Let's see it in action with the array [2, 4, 5, 7, 9] searching for 7:
⏱ Time Complexity: O(n) — In the worst case, your friend is the very last person in the crowd (or not there at all!), so you check every single element. If the array has n elements, that's up to n comparisons.
💾 Space Complexity: O(1) — You're just walking through the crowd with your own two eyes. No extra data structures needed. Just you and a loop. 🚶
Linear search might sound basic, but it's the building block for everything that comes next. Before you can find duplicates, pairs, or patterns — you need to know how to scan through an array like a pro. Let's do it!
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
print(f"Found 7 at index {linear_search([2, 4, 5, 7, 9], 7)}")
target = 99
print(f"Found {linear_search([2, 4, 5, 7, 9], target)} for target {target}")
print(f"Found 1 at index {linear_search([1, 3, 5], 1)}")