Count Empty Seats
Given an array representing seats in a venue where 0 means empty and 1 means occupied, count how many seats are empty. Return the total number of empty seats.
For example, seats [0, 1, 0, 0, 1] has 3 empty seats. All occupied [1, 1, 1] has 0 empty seats. All empty [0, 0, 0] has 3 empty seats. An empty array returns 0.
Counting elements that match a value is a fundamental aggregation pattern. It applies to inventory counting, survey response tallying, error log analysis, and many data processing tasks.
The solution initializes a counter to 0 and iterates through each seat value. Whenever the value is 0, increment the counter. After the loop, return the total count.
Edge cases include an empty array (return 0), all seats full (return 0), and all seats empty (count equals array length).
Example Input & Output
There are three empty seats in the row.
All seats are occupied, so none are empty.
With no seats in the list, the empty count stays 0.
Algorithm Flow
Solution Approach
Iterate through the array and count elements equal to 0.
Initialize count to 0. Loop through each seat value. If the value is 0 (meaning the seat is empty), increment the counter. After the loop finishes, return the total count of empty seats found. This works correctly for empty arrays because the loop body never executes and count remains 0.
Time complexity is O(n), space complexity is O(1).
Best Answers
program count_empty_seats
dictionary
seats: array[1..100] of integer
empty_count, i, n: integer
algorithm
input(seats)
empty_count <- 0
n <- seats.length
for i <- 0 to n - 1 do
if seats[i] = 0 then
empty_count <- empty_count + 1
endif
endfor
output(empty_count)
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
