Can You Feed These Hungry Students On LeetCode?
A Peek Into Arrays, Stacks, Queues & Deques
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) and1
(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
andsandwiches
, 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 thestudents
array,j = 0
is the front of the queue.