JAVA | Stack & Queue | Commented explanation ✅
Please Upvote :D\njava []\nclass Solution {\n    public int countStudents(int[] students, int[] sandwiches) {\n        // We create a stack and the queue to sim
# Please Upvote :D\n``` java []\nclass Solution {\n    public int countStudents(int[] students, int[] sandwiches) {\n        // We create a stack and the queue to simulate the serving process\n        Stack<Integer> sandwichStack = new Stack<>();\n        Queue<Integer> studentQueue = new LinkedList<>();\n        // populate the stack and the queue\n        for (int i = 0; i < students.length; i++) {\n            sandwichStack.push(sandwiches[sandwiches.length-i-1]);\n            studentQueue.offer(students[i]);\n        }\n\n        int couldntServe = 0;   // number of students that\'ll be left hungry\n        while (true) {\n            if (sandwichStack.peek() == studentQueue.peek()) {  // if types match\n                couldntServe = 0;       // served the current student\n                sandwichStack.pop();    // sandwich served\n                studentQueue.poll();    // student moves out of queue\n            } else {\n                couldntServe++;         // couldnt serve so increment count\n                studentQueue.offer(studentQueue.poll());    // move the student to the end of queue\n            }\n\n            // the unserved students will keep accumulating the the back of the queue\n            // until a situation would occur when we won\'t be able to serve them anymore due to type mismatch\n            // the queue will be left with only unservable students\n            if (couldntServe == studentQueue.size()) {  // that\'s when this condition would be hit\n                break;\n            }\n        }\n\n        return couldntServe;    // return the number of unserved students\n    }\n}\n\n// TC: O(n), SC: O(n)\n```
['Array', 'Stack', 'Queue', 'Simulation', 'Java']