Number of Students unable to eat Lunch


1700. Number of Students Unable to Eat Lunch – LeetCode


Problem Statement

The school cafeteria offers lunch with two types of sandwiches:

Each student prefers either type 0 or type 1. All students stand in a queue. At each step:

This process continues until none of the students want the top sandwich.

Return the number of students unable to eat.


Examples

Example 1:

Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
Output: 0
Explanation:
- Student 0 (1) doesn't want 0 → move to back
- Student 1 (1) doesn't want 0 → move to back
- Student 2 (0) takes 0 → leaves
- Student 3 (0) takes 0 → leaves
- Student 0 (1) takes 1 → leaves
- Student 1 (1) takes 1 → leaves
All students are served

Example 2:

Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
Output: 3

Constraints


Intuition

Instead of simulating the entire queue rotation (which could be slow and repetitive), observe that:


Approach: Greedy with Count Tracking

  1. Count how many students want:

    • cir → circular sandwiches (0)

    • sqr → square sandwiches (1)

  2. Traverse through the sandwiches array:

    • If the current top is 0 and cir > 0, serve one → cir--

    • If the current top is 1 and sqr > 0, serve one → sqr--

    • If the top sandwich has no matching student, return cir + sqr

  3. If all are served, return 0


Java Code

class Solution {
    public int countStudents(int[] students, int[] sandwiches) {
        int cir = 0;
        int sqr = 0;

        for (int i : students) {
            if (i == 1) sqr++;
            else cir++;
        }

        for (int i : sandwiches) {
            if (i == 1 && sqr > 0) {
                sqr--;
            } else if (i == 0 && cir > 0) {
                cir--;
            } else {
                return cir + sqr;
            }
        }

        return 0;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation Just counting preferences and iterating through sandwiches

Dry Run

Input:

students = [1,1,1,0,0,1]
sandwiches = [1,0,0,0,1,1]

Counters:

Processing:


Conclusion

This problem can be efficiently solved using counting instead of full queue simulation. It teaches a key competitive programming insight:

If a simulation involves only matching of types, frequency counting often leads to linear-time solutions.