
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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int CountStudents(int[] students, int[] sandwiches) {
6 Queue<int> queue = new Queue<int>(students);
7 int j = 0, cycle_count = 0;
8 while (queue.Count > 0 && cycle_count < queue.Count) {
9 if (queue.Peek() == sandwiches[j]) {
10 queue.Dequeue();
11 j++;
12 cycle_count = 0;
13 } else {
14 queue.Enqueue(queue.Dequeue());
15 cycle_count++;
16 }
17 }
18 return queue.Count;
19 }
20
21 public static void Main(string[] args) {
22 Solution solution = new Solution();
23 int[] students = {1, 1, 0, 0};
24 int[] sandwiches = {0, 1, 0, 1};
25 Console.WriteLine(solution.CountStudents(students, sandwiches));
26 }
27}In C#, this solution uses a Queue to simulate the students' preferences. Similar to other languages, it checks and rotates students through the queue while counting cycles to break early if needed.
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.
In JavaScript, the logic follows by counting student preferences and then checking each sandwich for availability decreases. If no more students want the specific sandwich, the remaining students count is returned.