
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 <stdio.h>
2#include <stdbool.h>
3
4int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) {
5 int count = 0;
6 int i = 0, j = 0;
7 int cycle_count = 0;
8 while (j < sandwichesSize && cycle_count < studentsSize) {
9 if (students[i] == sandwiches[j]) {
10 j++;
11 cycle_count = 0; // Reset cycle counter when a match happens
12 } else {
13 cycle_count++;
14 }
15 i = (i + 1) % studentsSize;
16 }
17 return studentsSize - j;
18}
19
20int main() {
21 int students[] = {1, 1, 0, 0};
22 int sandwiches[] = {0, 1, 0, 1};
23 int result = countStudents(students, 4, sandwiches, 4);
24 printf("%d\n", result);
25 return 0;
26}This C code defines a function that uses a circular iteration over the student preferences to check each against the current sandwich on the stack. We use two indices: one for students and one for sandwiches, plus a cycle counter to detect when all options are exhausted without making progress. The cycle count control helps to stop the loop when no further matches are possible, making the method more efficient.
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.
public class Solution {
public int CountStudents(int[] students, int[] sandwiches) {
int[] studentTypes = new int[2];
foreach (int student in students) {
studentTypes[student]++;
}
foreach (int sandwich in sandwiches) {
if (studentTypes[sandwich] > 0) {
studentTypes[sandwich]--;
} else {
return studentTypes[0] + studentTypes[1];
}
}
return 0;
}
public static void Main(string[] args) {
Solution solution = new Solution();
int[] students = {1, 1, 0, 0};
int[] sandwiches = {0, 1, 0, 1};
Console.WriteLine(solution.CountStudents(students, sandwiches));
}
}The C# implementation employs a similar logic by counting each type of student's preference using a size 2 array. For each sandwich, it attempts to find a match by decreasing the corresponding student type count.