Member-only story

Can You Feed These Hungry Students On LeetCode?

Dr. Ashish Bamania
3 min readMay 4, 2024

--

Generated with DALL-E 3

I recently came across an interesting problem on Leetcode.

It goes like this —

There’s a school cafeteria that offers two kinds of sandwiches (denoted with 0 (circular shaped) and 1 (square shaped).

These sandwiches are put in a Stack.

There’s a queue of hungry students who have a particular preference for either of these sandwiches.

The student at the front of the queue will pick up the sandwich from the sandwich stack, and only eat it if its shape matches his/ her preference (weird, but okay!).

If not, they will simply leave the sandwich back in the stack and join again at the queue’s end.

This process continues till none of the students in the queue wants a sandwich and thus they are unable to eat.

Given two integer arrays students and sandwiches, our challenge is to find out how many students are unable to eat.

Note that in the sandwiches array, i = 0 is the top of the stack while in the students array, j = 0 is the front of the queue.

My First Attempt

Since the sandwiches array is to be used as a Stack, a FILO (First-In, Last-Out) data structure, only the top element in it (at i = 0) can be removed at a time.

And the students array is to be used as a Queue, a FIFO (First-In, First-Out) data structure, so the elements are taken out from its front (at j = 0).

This was my first approach.

def countHungryStudents(students, sandwiches):
while students and sandwiches:
top_sandwich = sandwiches.pop(0)
front_student = students.pop(0)

if top_sandwich != front_student:
students.append(front_student)
else:
pass

return len(students)

I quickly realised that I was popping an element from sandwiches even when it did not match the student’s preference.

So, it fixed my code.

def countHungryStudents(students, sandwiches):
while students and sandwiches…

--

--

Dr. Ashish Bamania
Dr. Ashish Bamania

Written by Dr. Ashish Bamania

🍰 I simplify the latest advances in AI, Quantum Computing & Software Engineering for you | 📰 Subscribe to my newsletter here: https://intoai.pub

Responses (3)