
Sponsored
Sponsored
In this approach, we simulate the exact process of distributing sandwiches using a queue-like structure for the students. We repeatedly check if the student at the front of the queue can take the sandwich at the top of the stack. If not, the student is moved to the back of the queue. This continues until we complete a full cycle without any students taking a sandwich, indicating they can't eat.
Time Complexity: O(n^2) in the worst scenario because each student may be checked multiple times.
Space Complexity: O(1) since it only uses a fixed amount of extra space.
1#include <iostream>
2#include <vector>
3#include <queue>
4using namespace std;
5
6int countStudents(vector<int>& students, vector<int>& sandwiches) {
7 queue<int> studentQueue;
8 for (int student : students) {
9 studentQueue.push(student);
10 }
11 int j = 0, cycle_count = 0;
12 while (!studentQueue.empty() && cycle_count < studentQueue.size()) {
13 if (studentQueue.front() == sandwiches[j]) {
14 studentQueue.pop();
15 j++;
16 cycle_count = 0;
17 } else {
18 studentQueue.push(studentQueue.front());
19 studentQueue.pop();
20 cycle_count++;
21 }
22 }
23 return studentQueue.size();
24}
25
26int main() {
27 vector<int> students = {1, 1, 0, 0};
28 vector<int> sandwiches = {0, 1, 0, 1};
29 int result = countStudents(students, sandwiches);
30 cout << result << endl;
31 return 0;
32}This C++ code utilizes a standard queue from STL for managing the students. Every iteration compares the student at the front of the queue with the top sandwich. If they match, the student is removed and the cycle count is reset. If they don't match, the student is moved to the back of the queue and the cycle count increments. This approach continues until the sandwich pile or queue is exhausted.
This approach uses counting to determine if students can satisfy their preferences before iterating over sandwiches. By counting the number of students preferring each type, we can efficiently determine how many students will be unable to eat if sandwiches of their preference run out before they can eat.
Time Complexity: O(n) because it processes each list one time.
Space Complexity: O(1) since it only uses fixed additional space for counting.
This Java solution uses an array to count the number of student preferences for each type. It then attempts to match these against the sandwiches. If any mismatch occurs, it returns the number of students left unmet.