We simulate the lunch process exactly as described. Students form a queue and take the top sandwich only if it matches their preference; otherwise, they go to the back of the queue. The process stops when the top sandwich cannot be taken by anyone remaining in the queue. A queue data structure naturally models students rotating until a match is found.
class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
n = len(students)
q = deque(students)
res = n
for sandwich in sandwiches:
cnt = 0
while cnt < n and q[0] != sandwich:
cur = q.popleft()
q.append(cur)
cnt += 1
if q[0] == sandwich:
q.popleft()
res -= 1
else:
break
return resInstead of using a separate queue, we can simulate the rotation using a circular index on the original students array. When a student takes a sandwich, we mark their position as served (using -1). This avoids the overhead of queue operations while achieving the same behavior.
n checks.-1 and decrement the remaining count.class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
n = len(students)
idx = 0
res = n
for sandwich in sandwiches:
cnt = 0
while cnt < n and students[idx] != sandwich:
idx += 1
idx %= n
cnt += 1
if students[idx] == sandwich:
students[idx] = -1
res -= 1
else:
break
return resThe key insight is that student order does not matter. Since students can rotate indefinitely, what matters is whether there exists any student who wants the current top sandwich. If we track how many students want each type (0 or 1), we can quickly check availability without simulating the queue.
The naive approach of simulating the full queue rotation process leads to O(n^2) time complexity. The key insight is that student order does not matter since they can rotate indefinitely. Simply counting how many students prefer each sandwich type is sufficient.
The process stops when the top sandwich cannot be taken by any remaining student, not when all sandwiches are processed. If no student wants the current top sandwich, all remaining students will be unable to eat, even if later sandwiches in the stack match their preferences.