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:

  1. Category enum (Category): Define an enumeration with exactly three members in this declaration order: APPETIZER, MAIN, and DESSERT.
  2. Dish model (MenuItem): Store each dish's name, numeric price, and Category, 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 at 13 in MAIN formats as "Ramen | $13.00 | MAIN".
  3. Command replay (manage_menu(operations, arguments)): Instantiate a single empty menu, run each command in operations with its corresponding parameter list from arguments, and return a list containing one result per command:
    • "addItem" with [name, price, category]: Insert a new dish and return True. Return False (without altering the menu) if name already exists anywhere on the menu, category is not one of "APPETIZER", "MAIN", or "DESSERT", or price is invalid.
    • "updatePrice" with [name, new_price]: Change the price of an existing dish and return True. Return False (keeping the old price) if name is not on the menu or new_price is invalid.
    • "removeItem" with [name]: Delete name from the menu and return True (allowing name to be added again later). Return False if name is absent.
    • "listByCategory" with [category]: Return a List[str] of formatted dish strings belonging to category, ordered lexicographically (ASCII order) by name. If category is invalid or currently holds no dishes, return [].
    • "listAll" with []: Return a 3-element List[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 op in operations is one of "addItem", "updatePrice", "removeItem", "listAll", or "listByCategory".
  • Dish name and category arguments are strings; name is non-empty.
  • Prices passed in arguments are numeric values (int or float, potentially negative or non-finite in edge tests).

Step-by-step walkthrough

  1. Restate the problem and clarify the contracts

    We are building an in-memory menu manager where every dish has three attributes: a case-sensitive name string, a non-negative price, and one of three fixed categories (APPETIZER, MAIN, or DESSERT).

    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] True if added; False if name already exists, category is invalid, or price is invalid
    updatePrice [name, new_price] True if updated; False if name is missing or new_price is invalid
    removeItem [name] True if removed; False if name is missing
    listByCategory [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 order APPETIZER, MAIN, DESSERT (with [] for empty ones)

    Every dish string must follow the exact layout Dumplings | $7.50 | APPETIZER (always two decimal places) produced inside MenuItem.__str__ rather than formatting raw fields externally.

  2. 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 with for category in Category: also yields members in their exact declaration order (APPETIZER, MAIN, DESSERT), matching the group order required by listAll().

    We also centralize price checks in is_valid_price(price): - In Python, bool is a subclass of int (isinstance(True, int) evaluates to True), so we reject booleans explicitly. - Floating-point numbers include NaN ("Not a Number") and inf ("infinity"). Calling math.isfinite(price) filters out both before checking price >= 0. - One subtle floating-point detail: negative zero (-0.0, e.g., from float("-0")) satisfies -0.0 >= 0, yet f"{-0.0:.2f}" renders as "-0.00". Normalizing 0 to +0.0 inside MenuItem.__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}"
    
  3. 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), and removeItem(name) to scan up to n entries (O(n) instead of O(1)). - Keeping only one dictionary keyed by name makes mutations O(1), but listByCategory("MAIN") must inspect all n dishes on the menu just to collect the k mains (O(n + k log k) instead of O(k log k)). - Keeping only three per-category dictionaries means updatePrice(name) and removeItem(name) (which do not receive a category parameter) and addItem (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 MenuItem object: 1. self.items: maps name -> MenuItem across the whole menu. 2. self.by_category: maps each Category -> {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 MenuItem instance, updating item.price inside update_price automatically updates what by_category sees with zero risk of stale copies. And instead of maintaining pre-sorted lists (where inserting or deleting shifts up to k elements in O(k) time), we sort the k keys on demand inside list_category, preserving O(1) writes and O(k log k) category reads.

  4. 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, and name not in self.items before mutating state so a rejected call leaves both dictionaries untouched. Otherwise construct one MenuItem and insert it into both maps. - update_price: Fetch self.items[name] in O(1) and overwrite .price on the shared instance. - remove_item: Pop the MenuItem from self.items in O(1), then read item.category to delete name directly from self.by_category[item.category] in O(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 True
    
  5. Implement `O(k log k)` category and full-menu listings

    To list one Category, we look up group = self.by_category[category], sort its k keys alphabetically (sorted(group.keys())), and format each MenuItem via str(group[name]) (which invokes MenuItem.__str__()). Items in other categories are never visited, so list_by_category runs in O(k log k) time.

    For list_all(), we iterate for category in Category: and append self.list_category(category). Empty categories return [], so list_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 groups
    
  6. Connect the judge replay wrapper and optional CLI helper

    We wrap Menu with manage_menu(operations, arguments) to dispatch each command name and collect its return value for the automated judge. We also include a lightweight run_cli(lines) helper (using shlex.split so 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 results
    
  7. Trace 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.DESSERT is empty, and iterating over Category keeps its [] slot at index 2.

  8. 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.items and self.by_category[category]). Because each MenuItem remembers its own category, 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 up self.by_category[category] in O(1) time, sort only its k dish names in O(k log k) comparisons, and call str(item) k times in O(k) without touching dishes from other categories.
  • listAll — Time: O(n log n) worst case. Summing O(k_i log k_i) across the three fixed categories (k_1 + k_2 + k_3 = n) performs at most O(n log n) work.
  • Space: O(n). Every active dish allocates one MenuItem instance and two dictionary references pointing to it, plus O(k) or O(n) temporary space for returned listing strings.

Edge cases

  • Empty categories in listAll(): Iterating over Category produces [] for any category with zero items (such as DESSERT in Example 1 after "Mochi" is removed), always returning a list of length 3.
  • Duplicate name in another category: "Gelato" added as DESSERT and then added again as APPETIZER returns False because self.items enforces uniqueness across the entire menu.
  • Remove followed by re-add: Once removeItem deletes a dish from both self.items and self.by_category, that name becomes available again — even under a different category.
  • Unknown category string: parse_category("BEVERAGE") returns None, causing addItem to return False and listByCategory to return [] safely without raising KeyError.
  • Price formatting and negative zero: Prices like 0, 12.5, and 3.456 format 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.0 so it renders as $0.00 instead 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.items and a separate copy in self.by_category means updatePrice updates one dictionary while listByCategory keeps printing the stale price from the other. Sharing one MenuItem instance prevents this completely.
  • Mutating state before finishing validation: Inserting into self.items before 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 < 0 alone: In IEEE-754 floating-point arithmetic, float("nan") < 0 evaluates to False, so if price < 0: return False accidentally accepts NaN! Pair math.isfinite(price) with price >= 0.
  • Formatting prices with round(price, 2) + str(...): str(round(7.5, 2)) produces "7.5" instead of "7.50". Always format display strings with f"{price:.2f}" inside MenuItem.__str__.
  • Filtering all n items inside listByCategory: Scanning self.items.values() for item.category == category degrades listByCategory from O(k log k) to O(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 makes listByCategory O(k) without sorting, but every addItem and removeItem shifts up to k list elements in O(k) time, breaking the O(1) mutation requirement.
  • Balanced binary search tree per category: A self-balancing tree (available in third-party libraries like sortedcontainers.SortedDict) gives O(log k) add/remove and O(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 use key as the dictionary key in both self.items and self.by_category[category], while keeping the original name inside MenuItem.name for __str__. That way "Ramen" and "ramen" collide as duplicates on addItem, match each other on updatePrice and removeItem, and sort case-insensitively when listing sorted(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 to None. Whenever add_item, update_price, or remove_item touches a dish in category, set self.cached_lines[category] = None to invalidate just that category's cache in O(1) time; on list_category, compute and store the sorted list only on a cache miss, and return a shallow copy (list(cached)) in O(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.2 is 0.30000000000000004, and halfway values like 2.675 can round unexpectedly to $2.67). Production billing systems store money either as fixed-point integer cents (storing $7.50 as the exact integer 750 and formatting f"${cents // 100}.{cents % 100:02d}") or with Python's decimal.Decimal configured with explicit currency rounding rules.

Follow-up questions

Similar questions

More CloudKitchens interview questions

All 7 CloudKitchens questions →