Problem Description
Given a queue of students each with a preference for either a circular (0) or square (1) sandwich, and a stack of sandwiches arranged such that the top sandwich is at index 0, simulate the process where the student at the front of the queue takes the sandwich if it matches their preference. If it does not match, the student moves to the end of the queue. The simulation stops when no student in the queue will take the top sandwich. The goal is to determine the number of students that are unable to eat.
Key Insights
- Instead of simulating every rotation of the queue, count the number of students preferring each type.
- The sandwiches are arranged in a stack (first element is the top); process them one by one.
- For each sandwich, if there is at least one student with a matching preference, decrement that count.
- As soon as a sandwich type is not available among the remaining students, the simulation stops.
Space and Time Complexity
Time Complexity: O(n) or O(n^2) in a naïve simulation; with the counting strategy it is O(n) where n is the number of students/sandwiches. Space Complexity: O(1) extra space (only a few counters are used).
Solution
We can solve the problem by using a counting approach instead of simulating the queue rotations. First, count how many students prefer each sandwich type (0 and 1). Then, iterate through the sandwich stack (from the top) and for each sandwich, check if there is a student with the matching preference. If yes, decrement that count; if not, break out of the loop, because no further sandwich can be taken. Finally, sum the remaining counts to get the number of students who are unable to eat.