Leetcode 1700. Number of Students Unable to Eat Lunch
The problem is defined on LeetCode as follows:
The school cafeteria offers circular and square sandwiches at lunch break, referred to as 0s and 1s respectively. All students stand in a queue. Each student either prefers square sandwiches 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:
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.
students
and sandwiches
arrays?
0
and 1
representing the types of sandwiches and student preferences.0
s and 1
s in the student’s preference list.public class Solution {
public int countStudents(int[] students, int[] sandwiches) {
int count0 = 0, count1 = 0;
// Count preference of students
for (int student : students) {
if (student == 0) count0++;
else count1++;
}
// Iterate through the sandwiches stack.
for (int sandwich : sandwiches) {
if (sandwich == 0) {
if (count0 > 0)
count0--;
else
return count1; // no students who prefer 0 left, return remaining students
} else {
if (count1 > 0)
count1--;
else
return count0; // no students who prefer 1 left, return remaining students
}
}
return 0; // All students could eat
}
}
n
is the number of students (or sandwiches).Thus, the total time complexity is O(n).
This solution efficiently uses counting and directly processes the sandwich stack, optimizing for both clarity and performance.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?