Number of Students Unable to Eat Lunch - Problem

The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.

The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:

  • If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.
  • Otherwise, they will leave it and go to the queue's end.

This continues until none of the queue students want to take the top sandwich and are thus unable to eat.

You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.

Input & Output

Example 1 — All Students Get Fed
$ Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
Output: 0
💡 Note: First student (wants 1) goes to back. Second student (wants 1) goes to back. Third student (wants 0) takes sandwich 0. Fourth student (wants 0) goes to back. Now sandwich 1 is available, first student takes it. Continue until all are fed.
Example 2 — Some Students Stuck
$ Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
Output: 3
💡 Note: After some students get their preferred sandwiches, remaining students all want type 1 but only type 0 sandwiches remain on top, so 3 students cannot eat.

Constraints

  • 1 ≤ students.length, sandwiches.length ≤ 100
  • students.length == sandwiches.length
  • sandwiches[i] is 0 or 1
  • students[i] is 0 or 1

Visualization

Tap to expand
Cafeteria Queue ProblemStudents Queue (preference):1100frontSandwich Stack:0101topMatch?Students cycle through queue until they get their sandwich or get stuck
Understanding the Visualization
1
Input
Students queue [1,1,0,0] and sandwich stack [0,1,0,1]
2
Process
Students either take matching sandwich or go to back of queue
3
Output
Count of students who remain unable to eat
Key Takeaway
🎯 Key Insight: Count preferences instead of simulating queue operations for O(n) efficiency
Asked in
Amazon 15 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen