KatInterview

Simulate a Cafeteria Serving Queue

Stacks & QueuesAuto-graded · 17 test cases
EasyAuto-gradedStacks & Queuesqueuesimulationdata structures

Last 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, where customers[i] is the item requested by customer i.
  • 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 customers is empty, return an empty list.

Constraints

  • 0 ≤ len(customers) ≤ 2000
  • 1 ≤ 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 customers appear as keys in stock.

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.