Number of Students Unable to Eat Lunch

In this problem, we simulate the process of students taking sandwiches. We use a queue to represent the line of students, and we use a list to represent the stack of sandwiches. The top of the stack is the first element in the list, and the front of the queue is the first element in the queue.

We keep looping until a condition is met: if a round of trying to distribute sandwiches ends and no sandwiches were taken, we break the loop. This condition represents that no more sandwiches can be taken by the remaining students, thus we return the count of the remaining students.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from collections import deque

class Solution:
    def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
        students = deque(students)
        sandwiches = deque(sandwiches)
        while True:
            taken = False
            for _ in range(len(students)):
                if students[0] == sandwiches[0]:  # The student takes the sandwich
                    students.popleft()
                    sandwiches.popleft()
                    taken = True
                else:  # The student goes to the end of the line
                    students.rotate(-1)
            if not taken:  # No sandwiches were taken in the last round
                break
        return len(students)

The deque class from the collections module in Python is used because it provides efficient operations for removing elements from and adding elements to both ends of a queue. The popleft method removes and returns the element at the front of the queue, and the rotate method rotates the elements in the queue a specified number of steps to the right. If the number of steps is negative, the elements are rotated to the left.