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
Visualization & algorithm
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
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each student either eats or is counted in one failed cycle. |
| Space | O(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)