Curriculum

Curriculum

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.

  1. 1Before the search
  2. 2Index 0 · S10
  3. 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.

Reveal the explanation
  1. Before the search

    Start at index 0 with 0 passes. The target is S24.

  2. Index 0 · S10

    S10 differs from S24. Count one pass and continue.

  3. 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

An attendance loop searches ["A1", "B2", "C3", "B2"] for "B2" and stops immediately on the first match. What are matchIndex and passesUsed?
Show the answer and reasoning

Correct answer matchIndex = 1, passesUsed = 2

Index 0 ("A1") does not match (pass 1). Index 1 ("B2") matches (pass 2), so the loop stops immediately at matchIndex = 1 after 2 passes.