Number of Students Unable to Eat Lunch — LeetCode 1700 Python Solution

EasyStackQueueArraySimulation
Problem
#1700
Pattern
Stack
Reading time
2 min

The problem

The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue.

Example

Input
students = [1,1,0,0], sandwiches = [0,1,0,1]
Output
0
Explanation
- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].

Python solution

Python
class Solution:
    def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
        cnt = Counter(students)
        for v in sandwiches:
            if cnt[v] == 0:
                return cnt[v ^ 1]
            cnt[v] -= 1
        return 0

Complexity

MeasureComplexity
TimeO(n), where n is the number of sandwiches
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1700. Number of Students Unable to Eat Lunch is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack and Queue.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1700. Number of Students Unable to Eat Lunch?
LeetCode 1700. Number of Students Unable to Eat Lunch is rated Easy on LeetCode.
What is the time complexity of LeetCode 1700. Number of Students Unable to Eat Lunch?
The Python solution on this page runs in O(n), where n is the number of sandwiches.
What is the space complexity of LeetCode 1700. Number of Students Unable to Eat Lunch?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1700. Number of Students Unable to Eat Lunch cover?
LeetCode 1700. Number of Students Unable to Eat Lunch is tagged Stack, Queue, Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview