QueueEasy

Students and Sandwiches Visualizer

What is Students and Sandwiches

Students stand in a queue. sandwiches[0] is the top sandwich. A student who wants that sandwich takes it and leaves. A student who does not want it goes to the rear. Return how many students cannot eat.

Approach

Count skips. A successful take resets the skip count. When the skips equal the number of students still waiting, nobody wants the top sandwich.

Visualization & algorithm

Students waiting, and the sandwich stack
while students remain and a full cycle has not failed:
if front wants the top sandwich: both leave
else: front moves to the rear
return how many students remain
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each student either eats or is counted in one failed cycle.
SpaceO(n)The queue of students.

Implementation

from collections import deque
def solve(self, students, sandwiches):
    q = deque(students)
    i = skips = 0
    while q and skips < len(q):
        if q[0] == sandwiches[i]:
            q.popleft(); i += 1; skips = 0
        else:
            q.append(q.popleft()); skips += 1
    return len(q)