
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.
1import java.util.LinkedList;
2import java.util.Queue;
3
4public class Solution {
5 public int countStudents(int[] students, int[] sandwiches) {
6 Queue<Integer> queue = new LinkedList<>();
7 for (int student : students) {
8 queue.offer(student);
9 }
10 int j = 0, cycle_count = 0;
11 while (!queue.isEmpty() && cycle_count < queue.size()) {
12 if (queue.peek() == sandwiches[j]) {
13 queue.poll();
14 j++;
15 cycle_count = 0;
16 } else {
17 queue.offer(queue.poll());
18 cycle_count++;
19 }
20 }
21 return queue.size();
22 }
23
24 public static void main(String[] args) {
25 Solution solution = new Solution();
26 int[] students = {1, 1, 0, 0};
27 int[] sandwiches = {0, 1, 0, 1};
28 System.out.println(solution.countStudents(students, sandwiches));
29 }
30}The Java solution also employs a Queue for student representation. It follows a similar loop as described for C++ code, leveraging Java's queue operations to circulate around the student list and identify potential matches with the current sandwich.
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.