Step 3: Solve Problems on Arrays [Easy -> Medium -> Hard]›Easy
Linear Search & The Flashlight Sweep
EasyFunction: linearSearch()
ASCI Mission Breakdown • Simple as Hell
"Scan array from left to right to find the index of target number, or return -1."
Real-World Metaphor:
Looking for your car in an open parking lot row. You walk down from stall 0 to stall n-1. If you see your car at stall 4, you stop and report stall 4.
Interactive Visual WalkthroughARRAY-POINTERS
Step 1 / 2
Lockers: [1, 2, 3, 4, 5] | Target = 3
i
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
Memory Notepad / State Tracker
Current:1
Target:3
Evaluating
1. Shine Flashlight on Locker 0
Locker 0 holds 1. Target is 3. Mismatch! Advance flashlight.
How to Think About This (Mental Model)
Loop through array from i = 0 to nums.length - 1.
If nums[i] === num, return i immediately.
If loop completes without finding it, return -1.
### The Mission
Imagine a row of storage lockers. You are looking for a locker containing a specific item code **num**.
Take your flashlight and shine it into each locker from left to right. As soon as you find the locker containing **num**, return its index position. If you check every single locker and it is not there, return **-1**.
Examples
Example 1
Input: nums = [1,3,5,6], target = 5
Output: 2
Explanation: 5 is found at index 2.
Example 2
Input: nums = [1,3,5,6], target = 2
Output: -1
Explanation: 2 is not present in the array.
Constraints
1 <= nums.length <= 10^5
-10^9 <= nums[i], target <= 10^9
Topic Tags:
Solve Problems on Arrays [Easy -> Medium -> Hard]EasylinearSearch