Simulate a Cafeteria Serving Queue
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests the ability to simulate a round-robin service queue where customers cycle back if unserved, tracking when each customer is finally served.
Cafeteria Serving Queue
A cafeteria has a single serving counter. Customers arrive and join a queue in order. The server works through the queue one customer at a time, but the server can only fulfill a request if they have enough of that item in stock.
Each customer requests exactly one item type (identified by a string) and one unit of it. The server checks the front of the queue:
- If the requested item is in stock (stock count > 0), the server serves that customer (decrements stock by 1) and the customer leaves the queue. Record the turn number (1-indexed, incremented each time the server attends to the front of the queue) at which this customer was served.
- If the requested item is out of stock, the customer moves to the back of the queue. The turn counter still increments.
This continues until all customers have been served.
You are given:
customers: a list of strings, wherecustomers[i]is the item requested by customeri.stock: a dict mapping item name → initial stock count (non-negative integer).
Return a list of integers result where result[i] is the turn number on which customer i was served.
Notes:
- Every item requested by some customer is guaranteed to appear as a key in
stock. - The total stock across all items is guaranteed to be enough to serve every customer (no customer is stranded forever). More precisely, for each item, the number of customers requesting it is exactly equal to the stock count for that item.
- If
customersis empty, return an empty list.
Constraints
0 ≤ len(customers) ≤ 20001 ≤ len(item name) ≤ 20(lowercase letters only)0 ≤ stock[item] ≤ 2000- For each item,
stock[item]equals the number of customers requesting that item. - All item names in
customersappear as keys instock.
Examples
Example 1
Input: cafeteria_serving_order(['soup', 'salad', 'soup', 'salad'], {'soup': 2, 'salad': 2})
Output: [1, 2, 3, 4]
Example 2
Input: cafeteria_serving_order(['pizza', 'pasta', 'pizza'], {'pizza': 2, 'pasta': 1})
Output: [1, 2, 3]
Example 3
Input: cafeteria_serving_order([], {})
Output: []
Hints
Hint 1
Use a `collections.deque` to efficiently pop from the front and append to the back.
Hint 2
Store (original_index, item) pairs in the queue so you can record the result at the correct position.
Hint 3
A turn counter increments every time the server looks at the front of the queue, whether the customer is served or sent to the back.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a direct queue simulation. The key insight is that we need to process customers in FIFO order, but customers who cannot be served cycle back to the end of the queue.
Algorithm:
- Initialize a
dequewith(original_index, item)pairs for every customer in arrival order. - Maintain a
turncounter starting at 0 and aresultarray of sizen. - While the queue is non-empty:
- Increment
turn. - Pop the front element
(idx, item). - If
stock[item] > 0: serve the customer — decrement stock, recordresult[idx] = turn. - Otherwise: push
(idx, item)back to the end of the queue.
- Increment
- Return
result.
Why it is correct:
The turn counter captures every "server attention" event, whether or not service was rendered. Because each item's stock exactly equals the number of customers requesting it, every customer will eventually be served (no infinite loop). The deque gives O(1) front-pop and back-append, faithfully modelling the queue cycling behavior.
Complexity:
- Let n = number of customers and S = total stock = n.
- In the worst case (e.g., one item with large stock, all same item at the front while another is empty), the queue can cycle many times. However, every "unsuccessful" turn will eventually become successful once preceding customers of that type are served.
- Worst-case turns: O(n²) (consider n/2 customers for item A, n/2 for item B, interleaved such that one type must wait for all of the other).
- Time complexity: O(n²) in the worst case; O(n) in the best case (all items always in stock).
- Space complexity: O(n) for the deque and result array.
For n ≤ 2000, O(n²) = 4,000,000 operations, well within limits.
from collections import deque
def cafeteria_serving_order(customers: list, stock: dict) -> list:
if not customers:
return []
stock = dict(stock) # copy to avoid mutating input
result = [0] * len(customers)
queue = deque((i, item) for i, item in enumerate(customers))
turn = 0
while queue:
turn += 1
idx, item = queue.popleft()
if stock[item] > 0:
stock[item] -= 1
result[idx] = turn
else:
queue.append((idx, item))
return result