Keep a Running Count Across a List
Scenario
Count how many study rooms have at least 1 free seat in freeSeatList = [0, 2, 1, 0].
- 1Start: openRooms = 0 -> room 0 has 0 seats
- 2Room 1 has 2 seats (2 > 0 is true)
- 3Room 2 has 1 seat (1 > 0 is true)
- 4Room 3 has 0 seats -> loop ends
Try it yourself
Step through each room and track openRooms from 0 to its final value.
| Case | State after the step |
|---|---|
| Start: openRooms = 0 -> room 0 has 0 seats | — |
| Room 1 has 2 seats (2 > 0 is true) | — |
| Room 2 has 1 seat (1 > 0 is true) | — |
| Room 3 has 0 seats -> loop ends | — |
Reveal the explanation
- Start: openRooms = 0 -> room 0 has 0 seats
0 > 0 is false. openRooms remains 0.
- Room 1 has 2 seats (2 > 0 is true)
Increment counter: openRooms becomes 1.
- Room 2 has 1 seat (1 > 0 is true)
Increment counter: openRooms becomes 2.
- Room 3 has 0 seats -> loop ends
0 > 0 is false. Final returned openRooms = 2.
Two common mistakes break counters: resetting count = 0 inside the loop body, or adding the room’s seat count when you meant to count matching rooms (+1).
Download shared test cases
Your turn
Trace both countOpenRooms([0, 2, 1]) and totalFreeSeats([0, 2, 1]) and contrast the two final numbers.
Common mistake Adding seats (+ item) when the rule asks for the number of open rooms (+ 1).
Check your work
countOpenRooms -> 2 rooms; totalFreeSeats -> 3 seats.
Quick check
This browser could not save your progress. Changes last until you leave the page.