Stop a Loop Early When You Find a Match
Scenario
An attendance checker scans a list of student IDs from index 0 forward to see if targetId is present. As soon as the current ID equals targetId, the loop stops.
- 1Before the search
- 2Index 0 · S10
- 3Index 1 · S24
Try it yourself
If roster = ["S10", "S24", "S31", "S24"] and targetId = "S24", predict which index and how many passes the early-stop loop uses.
| Case | State after the step |
|---|---|
| Before the search | — |
| Index 0 · S10 | — |
| Index 1 · S24 | — |
Reveal the explanation
- Before the search
Start at index 0 with 0 passes. The target is S24.
- Index 0 · S10
S10 differs from S24. Count one pass and continue.
- Index 1 · S24
Match. Return index 1 after 2 passes. The second S24 is never inspected.
Early exit turns worst-case full scans into fast best-case stops when a match appears near the front, and guarantees matchIndex points to the first occurrence rather than a later duplicate.
Download shared test cases
Your turn
Trace an event waitlist loop scanning slots = ["taken", "free", "free", "taken"] for target = "free". Record the index checked on each pass and the pass number where it stops.
Common mistake Scanning the whole list even after finding "free" at index 1, which uses 4 passes and overwrites matchIndex with 2.
Check your work
Trace showing Pass 1 checks index 0 ("taken"), Pass 2 checks index 1 ("free"), sets matchIndex = 1, and stops after 2 passes.
Quick check
This browser could not save your progress. Changes last until you leave the page.