from collections import deque class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: # More optimal to pop from right of lists sandwiches = sandwiches[::-1] # For optimal queue operations, we need a deque students = deque(students) # Constraint given in problem statement max_length = 100 i = 0 while sandwiches and i <= max_length: # Happy path! if students[0] == sandwiches[-1]: i = 0 students.popleft() sandwiches.pop() # Else, send student to end of the queue and start # incrementing counter until we hit max_length else: students.append(students.popleft()) i += 1 return len(students) Complexity Time: O(n) Space: O(n) — depends I guess, but in this case, we had to make a deque data structure