Enum-Driven Restaurant Menu Manager
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an in-memory restaurant menu service that groups dishes under a fixed set of categories and executes a sequence of CRUD and listing commands efficiently.
Model the menu using three core components:
- Category enum (
Category): Define an enumeration with exactly three members in this declaration order:APPETIZER,MAIN, andDESSERT. - Dish model (
MenuItem): Store each dish'sname, numericprice, andCategory, and format display lines inside the object's own string conversion method (__str__) rather than assembling fields externally. Every formatted dish string must follow:text <name> | $<price_with_two_decimals> | <CATEGORY>For example, a dish named"Ramen"priced at13inMAINformats as"Ramen | $13.00 | MAIN". - Command replay (
manage_menu(operations, arguments)): Instantiate a single empty menu, run each command inoperationswith its corresponding parameter list fromarguments, and return a list containing one result per command:"addItem"with[name, price, category]: Insert a new dish and returnTrue. ReturnFalse(without altering the menu) ifnamealready exists anywhere on the menu,categoryis not one of"APPETIZER","MAIN", or"DESSERT", orpriceis invalid."updatePrice"with[name, new_price]: Change the price of an existing dish and returnTrue. ReturnFalse(keeping the old price) ifnameis not on the menu ornew_priceis invalid."removeItem"with[name]: Deletenamefrom the menu and returnTrue(allowingnameto be added again later). ReturnFalseifnameis absent."listByCategory"with[category]: Return aList[str]of formatted dish strings belonging tocategory, ordered lexicographically (ASCIIorder) byname. Ifcategoryis invalid or currently holds no dishes, return[]."listAll"with[]: Return a 3-elementList[List[str]]containing the sorted category listings in exact enum order[APPETIZER, MAIN, DESSERT], using[]for any category that currently has zero dishes.
Validation and complexity rules:
- Dish names are case-sensitive and globally unique across all categories combined.
- A valid price is a finite real number (int or float, excluding bool, NaN, and positive/negative infinity) satisfying price >= 0. Negative zero (-0.0) is accepted and must display as $0.00.
- addItem, updatePrice, and removeItem must each run in $O(1)$ average time, and listByCategory must run in $O(k \log k)$ time where $k$ is the number of dishes currently in that single category.
Examples
Example 1
Input:
operations = ["addItem", "addItem", "addItem", "listAll", "updatePrice", "listByCategory", "removeItem", "listAll"]
arguments = [
["Dumplings", 7.5, "APPETIZER"],
["Ramen", 13, "MAIN"],
["Mochi", 5.25, "DESSERT"],
[],
["Ramen", 14.75],
["MAIN"],
["Mochi"],
[]
]
Output:
[
True,
True,
True,
[["Dumplings | $7.50 | APPETIZER"], ["Ramen | $13.00 | MAIN"], ["Mochi | $5.25 | DESSERT"]],
True,
["Ramen | $14.75 | MAIN"],
True,
[["Dumplings | $7.50 | APPETIZER"], ["Ramen | $14.75 | MAIN"], []]
]
Explanation: Three dishes are added across the three categories and listed in enum order [APPETIZER, MAIN, DESSERT]. Updating "Ramen" to 14.75 immediately reflects in listByCategory("MAIN"). After "Mochi" is removed, DESSERT becomes empty and appears as [] at index 2 of the final listAll output.
Example 2
Input:
operations = ["addItem", "addItem", "addItem", "listByCategory"]
arguments = [
["Tacos", 11, "MAIN"],
["Curry", 12.5, "MAIN"],
["Gnocchi", 15.2, "MAIN"],
["MAIN"]
]
Output:
[
True,
True,
True,
["Curry | $12.50 | MAIN", "Gnocchi | $15.20 | MAIN", "Tacos | $11.00 | MAIN"]
]
Explanation: All three MAIN dishes succeed on insertion and are returned in alphabetical order ("Curry", "Gnocchi", "Tacos") with prices formatted to two decimal places.
Example 3
Input:
operations = ["addItem", "addItem", "addItem", "updatePrice", "removeItem", "listAll"]
arguments = [
["Gelato", 6.5, "DESSERT"],
["Gelato", 9, "APPETIZER"],
["Soda", 3, "BEVERAGE"],
["Gelato", -4],
["Waffle"],
[]
]
Output:
[
True,
False,
False,
False,
False,
[[], [], ["Gelato | $6.50 | DESSERT"]]
]
Explanation: Once "Gelato" is added under DESSERT, adding "Gelato" again under APPETIZER fails because names are unique across the whole menu. Adding "Soda" to unknown category "BEVERAGE", setting a negative price -4, and removing missing "Waffle" all return False without modifying the stored "Gelato" entry.
Constraints
0 <= len(operations) == len(arguments) <= 100,000- Every
opinoperationsis one of"addItem","updatePrice","removeItem","listAll", or"listByCategory". - Dish
nameandcategoryarguments are strings;nameis non-empty. - Prices passed in
argumentsare numeric values (intorfloat, potentially negative or non-finite in edge tests).
Step-by-step walkthrough
Restate the problem and clarify the contracts
We are building an in-memory menu manager where every dish has three attributes: a case-sensitive
namestring, a non-negativeprice, and one of three fixed categories (APPETIZER,MAIN, orDESSERT).The automated judge calls
manage_menu(operations, arguments)to execute a sequence of commands on a single menu instance and collects one return value per call:Operation Arguments Expected return value addItem[name, price, category]Trueif added;Falseifnamealready exists,categoryis invalid, orpriceis invalidupdatePrice[name, new_price]Trueif updated;Falseifnameis missing ornew_priceis invalidremoveItem[name]Trueif removed;Falseifnameis missinglistByCategory[category]List[str]of formatted dishes in that category, sorted alphabetically by name ([]if invalid)listAll[]List[List[str]]of 3 category lists in enum orderAPPETIZER,MAIN,DESSERT(with[]for empty ones)Every dish string must follow the exact layout
Dumplings | $7.50 | APPETIZER(always two decimal places) produced insideMenuItem.__str__rather than formatting raw fields externally.Model fixed categories with an enum and format items in `__str__`
Why use an enum (short for enumeration — a type whose allowed values are a fixed, closed set of named constants) instead of arbitrary strings? An enum rejects unknown category labels like
"BEVERAGE"right at the input boundary, so every internal method can rely on receiving one of the three valid categories. In Python, iterating withfor category in Category:also yields members in their exact declaration order (APPETIZER,MAIN,DESSERT), matching the group order required bylistAll().We also centralize price checks in
is_valid_price(price): - In Python,boolis a subclass ofint(isinstance(True, int)evaluates toTrue), so we reject booleans explicitly. - Floating-point numbers includeNaN("Not a Number") andinf("infinity"). Callingmath.isfinite(price)filters out both before checkingprice >= 0. - One subtle floating-point detail: negative zero (-0.0, e.g., fromfloat("-0")) satisfies-0.0 >= 0, yetf"{-0.0:.2f}"renders as"-0.00". Normalizing0to+0.0insideMenuItem.__str__guarantees"$0.00".from enum import Enum import math from typing import Optional class Category(Enum): # Enum declaration order defines the exact group order returned by listAll(). APPETIZER = "APPETIZER" MAIN = "MAIN" DESSERT = "DESSERT" def parse_category(text: str) -> Optional[Category]: """Convert a raw category string into a Category enum member, or None if invalid.""" # Category.__members__ maps valid names ("APPETIZER", "MAIN", "DESSERT") to enum members. if text in Category.__members__: return Category[text] return None def is_valid_price(price: float) -> bool: """Return True if price is a real, finite, non-negative number.""" # In Python, bool is a subclass of int, so reject True/False explicitly. if isinstance(price, bool) or not isinstance(price, (int, float)): return False # math.isfinite rejects NaN and +/-inf before checking the >= 0 boundary. return math.isfinite(price) and price >= 0 class MenuItem: def __init__(self, name: str, price: float, category: Category): self.name = name self.price = float(price) self.category = category def __str__(self) -> str: # Normalize -0.0 (e.g., from float("-0") in CLI input) to +0.0 so it prints "$0.00", not "$-0.00". display_price = 0.0 if self.price == 0 else self.price return f"{self.name} | ${display_price:.2f} | {self.category.value}"Pick two hash maps that share the same `MenuItem` objects
Why can't a single container hit both complexity goals simultaneously? - Keeping one flat list of dishes forces
addItem(duplicate-name check),updatePrice(name), andremoveItem(name)to scan up tonentries (O(n)instead ofO(1)). - Keeping only one dictionary keyed bynamemakes mutationsO(1), butlistByCategory("MAIN")must inspect allndishes on the menu just to collect thekmains (O(n + k log k)instead ofO(k log k)). - Keeping only three per-category dictionaries meansupdatePrice(name)andremoveItem(name)(which do not receive a category parameter) andaddItem(which enforces global name uniqueness) must probe across all categories.We get the best of both worlds by maintaining two dictionary views pointing to the exact same
MenuItemobject: 1.self.items: mapsname -> MenuItemacross the whole menu. 2.self.by_category: maps eachCategory -> {name -> MenuItem}for dishes in that category alone.self.items (global O(1) lookup by name) Shared MenuItem objects in memory +---------------+------------------------+ +----------------------------------------+ | "Dumplings" | -----------------------+-+-->| MenuItem("Dumplings", 7.5, APPETIZER) | | "Ramen" | ---------------------+ | | +----------------------------------------+ +---------------+----------------------+ | | +----------------------------------------+ +-|-+-->| MenuItem("Ramen", 13.0, MAIN) | self.by_category (grouped for listing) | | +----------------------------------------+ Category.APPETIZER: {"Dumplings": -----|-+} Category.MAIN: {"Ramen": ---------+ } Category.DESSERT: {}Because both dictionaries hold references to the same
MenuIteminstance, updatingitem.priceinsideupdate_priceautomatically updates whatby_categorysees with zero risk of stale copies. And instead of maintaining pre-sorted lists (where inserting or deleting shifts up tokelements inO(k)time), we sort thekkeys on demand insidelist_category, preservingO(1)writes andO(k log k)category reads.Implement `O(1)` add, update, and remove
Each mutation performs a constant number of hash-map lookups or updates: -
add_item: Verify the category enum, price validity, andname not in self.itemsbefore mutating state so a rejected call leaves both dictionaries untouched. Otherwise construct oneMenuItemand insert it into both maps. -update_price: Fetchself.items[name]inO(1)and overwrite.priceon the shared instance. -remove_item: Pop theMenuItemfromself.itemsinO(1), then readitem.categoryto deletenamedirectly fromself.by_category[item.category]inO(1).from typing import Dict class Menu: def __init__(self): # items: {name: MenuItem}, e.g. {"Ramen": MenuItem("Ramen", 13.0, Category.MAIN)} # Provides O(1) average lookup by item name across the entire menu. self.items: Dict[str, MenuItem] = {} # by_category: {Category: {name: MenuItem}}, sharing the SAME MenuItem objects as self.items # so listing one category only touches the k items in that category. self.by_category: Dict[Category, Dict[str, MenuItem]] = {} for category in Category: self.by_category[category] = {} def add_item(self, name: str, price: float, category_name: str) -> bool: category = parse_category(category_name) # Validate every rule before mutating state so a rejected add leaves both maps untouched. if category is None or not is_valid_price(price) or name in self.items: return False item = MenuItem(name, price, category) self.items[name] = item self.by_category[category][name] = item return True def update_price(self, name: str, new_price: float) -> bool: if name not in self.items or not is_valid_price(new_price): return False # Because self.items and self.by_category point to the same MenuItem instance, # updating item.price once makes the new price visible everywhere immediately. self.items[name].price = float(new_price) return True def remove_item(self, name: str) -> bool: if name not in self.items: return False # Pop from the global name map first, then use item.category to delete from its category map in O(1). item = self.items.pop(name) del self.by_category[item.category][name] return TrueImplement `O(k log k)` category and full-menu listings
To list one
Category, we look upgroup = self.by_category[category], sort itskkeys alphabetically (sorted(group.keys())), and format eachMenuItemviastr(group[name])(which invokesMenuItem.__str__()). Items in other categories are never visited, solist_by_categoryruns inO(k log k)time.For
list_all(), we iteratefor category in Category:and appendself.list_category(category). Empty categories return[], solist_all()always produces[appetizers, mains, desserts].from typing import List class MenuListingDemo: def list_category(self, category: Category) -> List[str]: group = self.by_category[category] # Sort only the k item names in this category -> O(k log k) time. sorted_names = sorted(group.keys()) lines = [] for name in sorted_names: # Format each item via str(item), which calls MenuItem.__str__(). lines.append(str(group[name])) return lines def list_by_category(self, category_name: str) -> List[str]: category = parse_category(category_name) if category is None: return [] return self.list_category(category) def list_all(self) -> List[List[str]]: # Iterate over the Category enum so empty categories still appear as [] in fixed order. groups = [] for category in Category: groups.append(self.list_category(category)) return groupsConnect the judge replay wrapper and optional CLI helper
We wrap
Menuwithmanage_menu(operations, arguments)to dispatch each command name and collect its return value for the automated judge. We also include a lightweightrun_cli(lines)helper (usingshlex.splitso quoted multi-word names stay intact) for interactive terminal runs.import shlex import sys from typing import List def manage_menu(operations: List[str], arguments: List[List]) -> List: # Replay the sequence of operations on one Menu instance and collect each return value. menu = Menu() results = [] for op, args in zip(operations, arguments): if op == "addItem": results.append(menu.add_item(args[0], args[1], args[2])) elif op == "updatePrice": results.append(menu.update_price(args[0], args[1])) elif op == "removeItem": results.append(menu.remove_item(args[0])) elif op == "listAll": results.append(menu.list_all()) elif op == "listByCategory": results.append(menu.list_by_category(args[0])) else: raise ValueError(f"unknown operation: {op}") return resultsTrace Example 1 step by step
Let's walk through all eight calls in Example 1 and watch both dictionaries stay synchronized:
1. addItem("Dumplings", 7.5, "APPETIZER") -> True items = {"Dumplings"} | by_category = {APP: {"Dumplings"}, MAIN: {}, DESSERT: {}} 2. addItem("Ramen", 13, "MAIN") -> True items = {"Dumplings", "Ramen"} | MAIN now has {"Ramen"} 3. addItem("Mochi", 5.25, "DESSERT") -> True items = {"Dumplings", "Ramen", "Mochi"} | DESSERT now has {"Mochi"} 4. listAll() -> [["Dumplings | $7.50 | APPETIZER"], ["Ramen | $13.00 | MAIN"], ["Mochi | $5.25 | DESSERT"]] 5. updatePrice("Ramen", 14.75) -> True Mutates shared MenuItem("Ramen").price from 13.0 to 14.75 in place 6. listByCategory("MAIN") -> ["Ramen | $14.75 | MAIN"] 7. removeItem("Mochi") -> True Pops "Mochi" from items; deletes "Mochi" from by_category[DESSERT] 8. listAll() -> [["Dumplings | $7.50 | APPETIZER"], ["Ramen | $14.75 | MAIN"], []]Notice step 8: after removing
"Mochi",Category.DESSERTis empty, and iterating overCategorykeeps its[]slot at index2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from enum import Enum import math import shlex import sys class Category(Enum): # Enum declaration order defines the exact group order returned by listAll(). APPETIZER = "APPETIZER" MAIN = "MAIN" DESSERT = "DESSERT" def parse_category(text: str) -> Optional[Category]: """Convert a raw category string into a Category enum member, or None if invalid.""" # Category.__members__ maps valid names ("APPETIZER", "MAIN", "DESSERT") to enum members. if text in Category.__members__: return Category[text] return None def is_valid_price(price: float) -> bool: """Return True if price is a real, finite, non-negative number.""" # In Python, bool is a subclass of int, so reject True/False explicitly. if isinstance(price, bool) or not isinstance(price, (int, float)): return False # math.isfinite rejects NaN and +/-inf before checking the >= 0 boundary. return math.isfinite(price) and price >= 0 class MenuItem: def __init__(self, name: str, price: float, category: Category): self.name = name self.price = float(price) self.category = category def __str__(self) -> str: # Normalize -0.0 (e.g., from float("-0") in CLI input) to +0.0 so it prints "$0.00", not "$-0.00". display_price = 0.0 if self.price == 0 else self.price return f"{self.name} | ${display_price:.2f} | {self.category.value}" class Menu: def __init__(self): # items: {name: MenuItem}, e.g. {"Ramen": MenuItem("Ramen", 13.0, Category.MAIN)} # Provides O(1) average lookup by item name across the entire menu. self.items: Dict[str, MenuItem] = {} # by_category: {Category: {name: MenuItem}}, sharing the SAME MenuItem objects as self.items # so listing one category only touches the k items in that category. self.by_category: Dict[Category, Dict[str, MenuItem]] = {} for category in Category: self.by_category[category] = {} def add_item(self, name: str, price: float, category_name: str) -> bool: category = parse_category(category_name) # Validate every rule before mutating state so a rejected add leaves both maps untouched. if category is None or not is_valid_price(price) or name in self.items: return False item = MenuItem(name, price, category) self.items[name] = item self.by_category[category][name] = item return True def update_price(self, name: str, new_price: float) -> bool: if name not in self.items or not is_valid_price(new_price): return False # Because self.items and self.by_category point to the same MenuItem instance, # updating item.price once makes the new price visible everywhere immediately. self.items[name].price = float(new_price) return True def remove_item(self, name: str) -> bool: if name not in self.items: return False # Pop from the global name map first, then use item.category to delete from its category map in O(1). item = self.items.pop(name) del self.by_category[item.category][name] return True def list_category(self, category: Category) -> List[str]: group = self.by_category[category] # Sort only the k item names in this category -> O(k log k) time. sorted_names = sorted(group.keys()) lines = [] for name in sorted_names: # Format each item via str(item), which calls MenuItem.__str__(). lines.append(str(group[name])) return lines def list_by_category(self, category_name: str) -> List[str]: category = parse_category(category_name) if category is None: return [] return self.list_category(category) def list_all(self) -> List[List[str]]: # Iterate over the Category enum so empty categories still appear as [] in fixed order. groups = [] for category in Category: groups.append(self.list_category(category)) return groups def manage_menu(operations: List[str], arguments: List[List]) -> List: # Replay the sequence of operations on one Menu instance and collect each return value. menu = Menu() results = [] for op, args in zip(operations, arguments): if op == "addItem": results.append(menu.add_item(args[0], args[1], args[2])) elif op == "updatePrice": results.append(menu.update_price(args[0], args[1])) elif op == "removeItem": results.append(menu.remove_item(args[0])) elif op == "listAll": results.append(menu.list_all()) elif op == "listByCategory": results.append(menu.list_by_category(args[0])) else: raise ValueError(f"unknown operation: {op}") return results def run_cli(lines) -> List[str]: """Execute text commands (one per line) on a fresh menu and return output lines. Supported commands: add <name> <price> <category> update <name> <price> remove <name> list list <category> """ menu = Menu() output = [] for line in lines: # shlex.split keeps quoted multi-word names together, e.g. add "Caesar Salad" 9 APPETIZER. try: words = shlex.split(line) except ValueError: output.append("error: unbalanced quotes") continue if not words: continue command = words[0].lower() try: if command == "add" and len(words) == 4: added = menu.add_item(words[1], float(words[2]), words[3]) if added: output.append("added") else: output.append("error: cannot add " + words[1]) elif command == "update" and len(words) == 3: updated = menu.update_price(words[1], float(words[2])) if updated: output.append("updated") else: output.append("error: cannot update " + words[1]) elif command == "remove" and len(words) == 2: removed = menu.remove_item(words[1]) if removed: output.append("removed") else: output.append("error: no item " + words[1]) elif command == "list" and len(words) == 1: for category, group in zip(Category, menu.list_all()): output.append(category.value + ":") for text in group: output.append(" " + text) elif command == "list" and len(words) == 2: if parse_category(words[1]) is None: output.append("error: unknown category " + words[1]) else: output.extend(menu.list_by_category(words[1])) else: output.append("error: bad command: " + line.strip()) except ValueError: # Triggered when float(...) receives non-numeric price text. output.append("error: bad price in: " + line.strip()) return output if __name__ == "__main__": for output_line in run_cli(sys.stdin): print(output_line)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing a kitchen's recipes with one physical index card per dish, referenced from two places at once: a master drawer sorted by dish name so the chef can find, reprice, or pull any dish immediately, and three small section binders (APPETIZER, MAIN, DESSERT) holding pointers to those exact same cards. In code, we represent the three fixed sections with an enum (short for enumeration — a closed type listing the exact allowed constants so invalid category names cannot sneak in) and build the two indexes with hash maps (dictionaries that look up, insert, or delete keys in O(1) average time using a key's hash). Both dictionaries hold shared object references (pointers to the exact same MenuItem instance in memory), and each MenuItem renders itself via __str__ (Python's string-conversion method that defines how str(item) formats the object as text).
Why do single-container designs fall short? Storing all dishes in one flat list forces addItem, updatePrice, and removeItem to scan up to n entries (O(n) instead of O(1)), and forces listByCategory to inspect dishes outside the requested category. Keeping only one dictionary keyed by name makes updates O(1), but listing a category of k dishes still scans all n menu items (O(n + k log k) instead of O(k log k)). Conversely, keeping only three separate per-category dictionaries breaks O(1) lookup on updatePrice(name) and removeItem(name) because neither call specifies which category the dish belongs to.
Here is a 4-step trace showing how items and by_category stay in sync automatically:
1. addItem("Tacos", 11, "MAIN") -> create obj1 = MenuItem("Tacos", 11.0, MAIN)
items["Tacos"] = obj1
by_category[MAIN]["Tacos"] = obj1
2. addItem("Curry", 12.5, "MAIN") -> create obj2 = MenuItem("Curry", 12.5, MAIN)
items["Curry"] = obj2
by_category[MAIN]["Curry"] = obj2
3. updatePrice("Tacos", 13.0) -> items["Tacos"].price = 13.0 (mutates obj1 in place!)
4. listByCategory("MAIN") -> sort keys ["Curry", "Tacos"], call str(...) on each:
["Curry | $12.50 | MAIN", "Tacos | $13.00 | MAIN"]
Complexity
Let n be the total number of dishes currently on the menu, and k be the number of dishes in one queried category (k <= n).
addItem,updatePrice,removeItem— Time:O(1)average. Each call validates inputs in constant time and performs at most two hash-map lookups, insertions, or deletions (self.itemsandself.by_category[category]). Because eachMenuItemremembers its owncategory,removeItem(name)deletes from the right category dictionary directly without probing all categories.listByCategory— Time:O(k log k)(assuming bounded dish-name lengths). We look upself.by_category[category]inO(1)time, sort only itskdish names inO(k log k)comparisons, and callstr(item)ktimes inO(k)without touching dishes from other categories.listAll— Time:O(n log n)worst case. SummingO(k_i log k_i)across the three fixed categories (k_1 + k_2 + k_3 = n) performs at mostO(n log n)work.- Space:
O(n). Every active dish allocates oneMenuIteminstance and two dictionary references pointing to it, plusO(k)orO(n)temporary space for returned listing strings.
Edge cases
- Empty categories in
listAll(): Iterating overCategoryproduces[]for any category with zero items (such asDESSERTin Example 1 after"Mochi"is removed), always returning a list of length 3. - Duplicate name in another category:
"Gelato"added asDESSERTand then added again asAPPETIZERreturnsFalsebecauseself.itemsenforces uniqueness across the entire menu. - Remove followed by re-add: Once
removeItemdeletes a dish from bothself.itemsandself.by_category, that name becomes available again — even under a different category. - Unknown category string:
parse_category("BEVERAGE")returnsNone, causingaddItemto returnFalseandlistByCategoryto return[]safely without raisingKeyError. - Price formatting and negative zero: Prices like
0,12.5, and3.456format to two decimal places ($0.00,$12.50,$3.46). Negative numbers,NaN,inf, and booleans are rejected. Negative zero (-0.0) is normalized to+0.0so it renders as$0.00instead of$-0.00. - Case-sensitive names: Standard string comparison treats
"ramen"and"Ramen"as distinct names and sorts uppercase ASCII letters (A-Z) before lowercase ones (a-z).
Common mistakes
- Storing two separate copies of a dish: Putting one tuple or object in
self.itemsand a separate copy inself.by_categorymeansupdatePriceupdates one dictionary whilelistByCategorykeeps printing the stale price from the other. Sharing oneMenuIteminstance prevents this completely. - Mutating state before finishing validation: Inserting into
self.itemsbefore checking whether the category or price is valid corrupts the menu when validation fails halfway through. Always check every precondition first. - Checking invalid prices with
price < 0alone: In IEEE-754 floating-point arithmetic,float("nan") < 0evaluates toFalse, soif price < 0: return Falseaccidentally acceptsNaN! Pairmath.isfinite(price)withprice >= 0. - Formatting prices with
round(price, 2)+str(...):str(round(7.5, 2))produces"7.5"instead of"7.50". Always format display strings withf"{price:.2f}"insideMenuItem.__str__. - Filtering all
nitems insidelistByCategory: Scanningself.items.values()foritem.category == categorydegradeslistByCategoryfromO(k log k)toO(n + k log k), which hurts when a small category (k = 2) sits inside a huge menu (n = 50,000).
Alternative approaches
- Sorted list per category (
bisect.insort): Keeping each category's names sorted at all times makeslistByCategoryO(k)without sorting, but everyaddItemandremoveItemshifts up toklist elements inO(k)time, breaking theO(1)mutation requirement. - Balanced binary search tree per category: A self-balancing tree (available in third-party libraries like
sortedcontainers.SortedDict) givesO(log k)add/remove andO(k)listing, trading slightly slower writes for faster reads.
Follow-up questions
- How would you enforce case-insensitive uniqueness on dish names while still displaying each dish's original capitalization? Normalize names with case-folding (
key = name.casefold(), a Unicode-aware lowercase conversion designed for case-insensitive matching) and usekeyas the dictionary key in bothself.itemsandself.by_category[category], while keeping the originalnameinsideMenuItem.namefor__str__. That way"Ramen"and"ramen"collide as duplicates onaddItem, match each other onupdatePriceandremoveItem, and sort case-insensitively when listingsorted(group.keys()). - If read queries (listAll and listByCategory) outnumber menu edits by several orders of magnitude, how would you speed up listing without sacrificing O(1) updates? Add a per-category cache
self.cached_lines: Dict[Category, Optional[List[str]]]initialized toNone. Wheneveradd_item,update_price, orremove_itemtouches a dish incategory, setself.cached_lines[category] = Noneto invalidate just that category's cache inO(1)time; onlist_category, compute and store the sorted list only on a cache miss, and return a shallow copy (list(cached)) inO(k)time on every repeat read. - Why is IEEE-754 floating-point arithmetic hazardous for monetary values, and how would you represent prices in a production ordering system? Binary floating-point numbers cannot represent most base-10 decimals exact to the cent (for example,
0.1 + 0.2is0.30000000000000004, and halfway values like2.675can round unexpectedly to$2.67). Production billing systems store money either as fixed-point integer cents (storing$7.50as the exact integer750and formattingf"${cents // 100}.{cents % 100:02d}") or with Python'sdecimal.Decimalconfigured with explicit currency rounding rules.
Follow-up questions
- How would you enforce case-insensitive uniqueness on dish names while still displaying each dish's original capitalization?
- If read queries (listAll and listByCategory) outnumber menu edits by several orders of magnitude, how would you speed up listing without sacrificing O(1) updates?
- Why is IEEE-754 floating-point arithmetic hazardous for monetary values, and how would you represent prices in a production ordering system?
Similar questions
- Top-K Frequencies Across Batch, Stream, and Sliding Windows
- In-Memory User File Store with Quota Eviction
- Point-of-Sale Receipt Engine with Promotional Bundles
- Thread-Safe Kitchen Order Queue and Pickup Coordinator
- Menu Tree Parser and Serializer
- Real-Time Kitchen Order Storage and Fulfillment Engine
More CloudKitchens interview questions
- In-Memory User File Store with Quota Eviction Medium
- Top-K Frequencies Across Batch, Stream, and Sliding Windows Medium
- Real-Time Kitchen Order Storage and Fulfillment Engine Medium Pro
- Point-of-Sale Receipt Engine with Promotional Bundles Medium Pro
- Thread-Safe Kitchen Order Queue and Pickup Coordinator Medium Pro
- Menu Tree Parser and Serializer Medium Pro