Tech for good

[Leetcode/Stack,Queue] 1700. Number of Students Unable to Eat Lunch 본문

IT/Computer Science

[Leetcode/Stack,Queue] 1700. Number of Students Unable to Eat Lunch

Diana Kang 2025. 4. 22. 00:56

# Example 1
students = [1,1,0,0], sandwiches = [0,1,0,1]
students = [1,0,0,1], sandwiches = [0,1,0,1]
students = [0,0,1,1], sandwiches = [0,1,0,1]
students = [0,1,1], sandwiches = [1,0,1]
students = [1,1,0], sandwiches = [1,0,1]
students = [1,0], sandwiches = [0,1]
students = [0,1], sandwiches = [0,1]
students = [1], sandwiches = [1]
students = [], sandwiches = []
Output: 0

# Example 2
students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
students = [1,1,0,0,1], sandwiches = [0,0,0,1,1]
students = [1,0,0,1,1], sandwiches = [0,0,0,1,1]
students = [0,0,1,1,1], sandwiches = [0,0,0,1,1]
students = [0,1,1,1], sandwiches = [0,0,1,1]
students = [1,1,1], sandwiches = [0,1,1]
Output: 3

🔁 deque (Double-Ended Queue)

A deque allows insertion and deletion from both ends.

Method Module Action
dq.appendleft(x) collections.deque Add element to the front of the deque
dq.append(x) collections.deque Add element to the back of the deque
dq.popleft() collections.deque Remove element from the front
dq.pop() collections.deque Remove element from the back

Use case: Useful when you need a queue or stack but with the flexibility of both ends.

📥 queue

A queue is First-In-First-Out (FIFO) — like people waiting in line.

Method Module Action
q.put(x) queue.Queue Add element to the back
q.get() queue.Queue Remove element from the front

Use case: When the first element added is the first one you want to remove.

📤 stack

A stack is Last-In-First-Out (LIFO) — like a stack of plates.

Method Module Action
stack.append(x) built-in list Add element to the top
stack.pop() built-in list Remove element from the top

Use case: When you want to reverse order or undo operations.

🔍 Summary Table

Data Structure Insertion Removal Direction
deque Front/Back Front/Back Double-ended
queue Back Front FIFO
stack Top Top LIFO
from typing import List
from collections import deque

class Solution:
    def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
        students = deque(students)      # queue: front = students[0]
        sandwiches = sandwiches[::-1]   # reverse to make it a stack: top = sandwiches[-1]

        count = 0  # number of unsuccessful rotations

        while students:
            if students[0] == sandwiches[-1]:
                students.popleft()
                sandwiches.pop()
                count = 0  # reset count when a sandwich is taken
            else:
                students.append(students.popleft())
                count += 1

            if count == len(students):
                break  # no one wants the current top sandwich

        return len(students)