Number of Students Unable to Eat Lunch

easy simulation counting

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.

Inputstudents = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
Output3
After eating the first three matches, all remaining students want 0 but the stack-top is 1 — three stay hungry.

def 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;
}
Time: O(n) Space: O(1)