💡
Exercise 7

Linear Search — Finding a Needle in a Haystack 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

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:

  • Start at the first element (index 0).
  • Compare each element with your target.
  • If you find it — awesome! Return the index immediately.
  • If you reach the end without finding it — return -1 (the universal "not found" signal).

Let's see it in action with the array [2, 4, 5, 7, 9] searching for 7:

# Searching for 7 in [2, 4, 5, 7, 9] # Index 0: 2 → nope # Index 1: 4 → nope # Index 2: 5 → nope # Index 3: 7 → FOUND IT! Return 3 ✅

⏱ 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!

📋 Instructions
Write a function `linear_search(arr, target)` that searches for `target` in `arr`. - Return the **index** of `target` if found. - Return **-1** if the target is not in the array. - Use a `for` loop — do NOT use Python's built-in `index()` or `in` operator. Then test it with these calls: ```python print(f"Found 7 at index {linear_search([2, 4, 5, 7, 9], 7)}") print(f"Found -1 for target {linear_search([2, 4, 5, 7, 9], 99)}") print(f"Found 1 at index {linear_search([1, 3, 5], 1)}") ```
Use a for loop with range(len(arr)) to check each element. If arr[i] == target, return i right away! If the loop finishes without returning, that means the target wasn't found — return -1.
⚠️ Try solving it yourself first — you'll learn more!
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)}")
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.