Number of Students Unable to Eat Lunch
Problem
Students queue with sandwich preferences 0/1; sandwiches sit on a stack. Front student takes the top if it matches, else moves to the back. Return how many students never eat.
students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]3def count_students(students, sandwiches):
cnt = [students.count(0), students.count(1)]
for s in sandwiches:
if cnt[s] == 0:
return cnt[0] + cnt[1]
cnt[s] -= 1
return 0
function countStudents(students, sandwiches) {
const cnt = [0, 0];
for (const s of students) cnt[s]++;
for (const s of sandwiches) {
if (cnt[s] === 0) return cnt[0] + cnt[1];
cnt[s]--;
}
return 0;
}
class Solution {
public int countStudents(int[] students, int[] sandwiches) {
int[] cnt = new int[2];
for (int s : students) cnt[s]++;
for (int s : sandwiches) {
if (cnt[s] == 0) return cnt[0] + cnt[1];
cnt[s]--;
}
return 0;
}
}
int countStudents(vector<int>& students, vector<int>& sandwiches) {
int cnt[2] = {0, 0};
for (int s : students) cnt[s]++;
for (int s : sandwiches) {
if (cnt[s] == 0) return cnt[0] + cnt[1];
cnt[s]--;
}
return 0;
}
Explanation
The clever observation is that the order of the students never matters — only how many want each kind of sandwich. So instead of simulating students rotating to the back of the line, we just keep two counts.
We tally cnt[0] (students who want type 0) and cnt[1] (students who want type 1). Then we walk through the sandwich stack from top to bottom. For each sandwich of type s, if someone still wants it (cnt[s] > 0), it gets eaten and we do cnt[s] -= 1.
The moment a sandwich type s appears but cnt[s] == 0, no remaining student will ever take it, so the line stalls forever. The number left hungry is simply cnt[0] + cnt[1].
Example: students [1,1,1,0,0,1] give cnt = [2, 4]. The sandwiches [1,0,0,0,1,1] get eaten one by one until a type-0 sandwich meets a moment when no type-0 students remain, leaving 3 students stuck.
It works because a student who does not want the top sandwich just keeps cycling without changing any count, so collapsing everything to counts gives the same answer far faster.