[LeetCode] Number of Students Unable to Eat Lunch

1700. Number of Students Unable to Eat Lunch

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 ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the jth student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int countStudents(vector<int>& students, vector<int>& sandwiches) {
vector<set<int>> st(2);
for(int i = 0; i < students.size(); i++) {
st[students[i]].insert(i);
}
int lst = -1;
for(auto& s : sandwiches) {
if(st[s].size() == 0) break;
auto it = st[s].lower_bound(lst);
if(it == end(st[s])) it = begin(st[s]);
lst = *it;
st[s].erase(it);
}
return st[0].size() + st[1].size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/08/PS/LeetCode/number-of-students-unable-to-eat-lunch/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.