Tensorum
LeetCode 1700 · Queue Simulation

Number of Students Unable to Eat Lunch

LeetCode 1700 · Easy · solution, intuition & step-by-step walkthrough

Stop when a full rotation makes no progress.

EasyArrayStackQueueSimulation
44 msruntime · beats 2%
48.7 MBmemory · beats 100%
1approach
1accepted runs · last 9 Apr 2024

This is how I solved Number of Students Unable to Eat Lunch (LeetCode 1700), an easy problem from the Queue Simulation pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Simulate the line: if the front student wants the top sandwich, both leave; otherwise the student goes to the back. If a whole lap passes with nobody taking a sandwich, the remaining students can never eat.

Approach

  1. 1

    Front matches top sandwich → remove both, reset the counter.

  2. 2

    Otherwise rotate the student to the back and count.

  3. 3

    Counter equals the queue length → stop.

  4. 4

    Return how many students remain.

How I solved it

Queue simulationPythonO(n²) time
class Solution:
    def countStudents(self, students, sandwiches):
        unable = 0
        while len(students):
            if students[0] == sandwiches[0]:
                students.pop(0)
                sandwiches.pop(0)
                unable = 0
            else:
                students.append(students.pop(0))
                unable += 1
                if unable == len(students):
                    break
        return len(students)
Loading the step-through…

Number of Students Unable to Eat Lunch — FAQ

What is the intuition behind Number of Students Unable to Eat Lunch?

Simulate the line: if the front student wants the top sandwich, both leave; otherwise the student goes to the back. If a whole lap passes with nobody taking a sandwich, the remaining students can never eat.

How do you solve Number of Students Unable to Eat Lunch (LeetCode 1700)?

1. Front matches top sandwich → remove both, reset the counter. 2. Otherwise rotate the student to the back and count. 3. Counter equals the queue length → stop. 4. Return how many students remain.

What is the time and space complexity of Number of Students Unable to Eat Lunch?

Time: O(n²). Space: O(1). (Accepted approach: Queue simulation.)

What are common mistakes in Number of Students Unable to Eat Lunch?

Counting each preference type gives O(n): stop when the top sandwich type has no takers.