In-Memory Recipe CRUD Store

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build an in-memory RecipeStore class that manages Recipe records with fast create, lookup, modification, and removal operations.

Each Recipe object holds four fields:

  • id (str): a string key formatted as "recipe<n>" (such as "recipe1", "recipe2", ...)
  • name (str): the display title of the dish
  • ingredients (List[str]): ordered ingredient strings
  • steps (List[str]): ordered preparation instructions

Implement the four methods on RecipeStore:

  • create(name: str, ingredients: List[str], steps: List[str]) -> Optional[str]
  • get(recipe_id: str) -> Optional[Recipe]
  • update(recipe_id: str, updated_recipe: Recipe) -> bool
  • delete(recipe_id: str) -> bool

Behavioral Rules

  1. Monotonic ID allocation: Accepted create calls receive "recipe1", "recipe2", "recipe3", ... in strict creation order starting at 1. A rejected create never advances the counter, and numbers from deleted recipes are never issued again.
  2. Strict ID parsing: get, update, and delete accept a string recipe_id and extract its numeric suffix. Only the exact lowercase prefix "recipe" followed by an ASCII base-10 integer n >= 1 with no leading zeros, whitespace, signs, or underscores is valid (for example, "recipe1" and "recipe15" are valid; "Recipe1", "recipe0", "recipe01", and "recipe 1" are invalid). Invalid or unknown IDs cause get to return None and update/delete to return False.
  3. Caseless title uniqueness: At most one active recipe may hold a given title when letter case is ignored (for instance, "RiSoTtO" and "risotto" conflict). If create receives a conflicting title, it leaves the store unchanged and returns None. Deleting a recipe releases its title for future creations.
  4. Stored casing preservation: get returns the recipe using the exact capitalization currently stored ("RiSoTtO" stays "RiSoTtO").
  5. Update validation & case-only title edits: update(recipe_id, updated_recipe) replaces name, ingredients, and steps and returns True if and only if:
    • recipe_id is well-formed and currently stored,
    • updated_recipe is non-None and updated_recipe.id == recipe_id (exact string match), and
    • updated_recipe.name differs from the stored recipe's name at most in letter casing (e.g., "RiSoTtO" to "Risotto" is valid, whereas "RiSoTtO" to "Gnocchi" fails). When a case-only title update succeeds, subsequent get calls return the newly saved casing; otherwise update returns False without altering stored state.
  6. State isolation: Mutating caller lists passed into create/update, or mutating a Recipe returned by get, must not alter internal store state.

Examples

Example 1

store = RecipeStore()
store.create("RiSoTtO", ["arborio rice", "broth"], ["toast rice", "ladle broth"])  -> "recipe1"
store.create("risotto", ["rice"], ["boil"])                                        -> None
store.create("Chili", ["beans", "tomatoes"], ["simmer"])                           -> "recipe2"
store.get("recipe1")                                                               -> Recipe("recipe1", "RiSoTtO", ["arborio rice", "broth"], ["toast rice", "ladle broth"])
store.update("recipe1", Recipe("recipe1", "Risotto", ["arborio rice", "broth", "parmesan"], ["toast rice", "ladle broth", "fold cheese"])) -> True
store.update("recipe1", Recipe("recipe1", "Gnocchi", ["potato"], ["boil"]))        -> False
store.get("recipe1")                                                               -> Recipe("recipe1", "Risotto", ["arborio rice", "broth", "parmesan"], ["toast rice", "ladle broth", "fold cheese"])
  • "risotto" collides with "RiSoTtO" ignoring case, so it returns None without consuming "recipe2".
  • Updating "RiSoTtO" to "Risotto" changes only capitalization and updates future reads, whereas renaming to "Gnocchi" is rejected.

Example 2

store = RecipeStore()
store.create("Waffles", ["flour", "milk"], ["whisk", "bake"])        -> "recipe1"
store.get("recipe01")                                                -> None
store.update("recipe1", Recipe("recipe2", "Waffles", ["flour"], [])) -> False
store.delete("recipe1")                                              -> True
store.get("recipe1")                                                 -> None
store.create("WAFFLES", ["oat flour"], ["cook"])                     -> "recipe2"
  • "recipe01" fails strict ID parsing due to its leading zero, and update fails when updated_recipe.id ("recipe2") does not match recipe_id ("recipe1").
  • Deleting "recipe1" frees the title "Waffles" so "WAFFLES" can be created under the next fresh ID "recipe2".

Constraints

  • Up to 10^5 total calls across create, get, update, and delete.
  • Each method should run in O(1) average lookup time with respect to the number of stored recipes (linear only in the size of the single recipe read or written).

Step-by-step walkthrough

  1. Understand the contract and edge rules

    We need to build an in-memory RecipeStore supporting CRUD operations (Create, Read, Update, and Delete) over Recipe(id, name, ingredients, steps) records:

    • create(name, ingredients, steps) -> Optional[str]: stores a new recipe and returns "recipe1", "recipe2", ..., or None if the title is already taken (ignoring letter case).
    • get(recipe_id) -> Optional[Recipe]: looks up a recipe by ID string, returning None if the ID format is invalid or does not exist.
    • update(recipe_id, updated_recipe) -> bool: updates a recipe in place, succeeding only when the ID exists, updated_recipe.id matches recipe_id character-for-character, and updated_recipe.name differs from the stored name only in letter case.
    • delete(recipe_id) -> bool: removes an existing recipe and returns True, or returns False if the ID is invalid or missing.

    Before writing code, settle four subtle edge rules from the specification and starter.py:

    1. Failed creates do not waste numbers: if "RiSoTtO" already exists, create("risotto", ...) returns None and the next valid recipe still gets "recipe2", not "recipe3".
    2. Deleted IDs are never reused: deleting "recipe1" frees the title "Waffles" for future recipes, but the counter keeps moving forward ("recipe2", "recipe3", ...) so old bookmarks never silently point to a different dish.
    3. Strict ID syntax: only "recipe" followed by a positive integer without leading zeros ("recipe1", "recipe42") is valid. Strings like "Recipe1", "recipe0", "recipe01", or "recipe 1" fail immediately.
    4. Defensive copies in and out: copying lists on create, get, and update prevents outside code from mutating a Recipe or ingredients list behind the store's back.
  2. Why a plain list is too slow

    The simplest possible store keeps a single Python list of Recipe objects:

    • create: loop through every stored recipe, compare existing.name.lower() == name.lower(), and append if no match is found.
    • get, update, delete: loop through the list until existing.id == recipe_id.

    If the store holds N recipes, every single method scans up to N entries (O(N) time per call). With 10 recipes that is unnoticeable; with 100,000 recipes every lookup or insert walks up to a hundred thousand objects. We can eliminate both linear scans by giving each lookup question its own hash map (Python dict).

  3. Design the two dictionaries and counter

    Every operation asks at most two fast lookup questions, so we maintain two synchronized dictionaries plus an integer counter:

    RecipeStore state after creating "RiSoTtO" and "Chili":
    
      next_number: 3
    
      recipes (Dict[int, Recipe])                 number_by_name (Dict[str, int])
      +---+------------------------------------+  +-----------+---+
      | 1 | Recipe("recipe1", "RiSoTtO", ...)  |  | "risotto" | 1 |
      | 2 | Recipe("recipe2", "Chili",   ...)  |  | "chili"   | 2 |
      +---+------------------------------------+  +-----------+---+
        ^                                                         |
        +------------------- points to same number ---------------+
    
    • self.recipes maps the parsed integer suffix (1, 2, ...) to the stored Recipe object, preserving the exact capitalization ("RiSoTtO") that get must return.
    • self.number_by_name maps the case-folded name ("risotto") to that recipe's integer suffix (1), letting create check in O(1) average time whether any casing of that name is already active.
    • self.next_number starts at 1 and increments only when create succeeds.

    We normalize names using Python's str.casefold(), which is a stricter version of str.lower() built specifically for case-insensitive matching across all Unicode text (for ASCII letters like "RiSoTtO" -> "risotto", both produce the exact same result; for characters like German "ß", casefold() also normalizes "Straße" and "STRASSE" to "strasse").

  4. Parse and validate recipe IDs strictly

    get, update, and delete all receive a string such as "recipe2" and must extract the positive integer 2. Slicing after "recipe" and calling int(digits) directly is a classic trap because Python's int() quietly accepts whitespace (" 7"), signs ("+7"), underscores ("1_0" -> 10), and leading zeros ("01" -> 1), while str.isdigit() alone also accepts non-ASCII Unicode digits like "١".

    Checking four simple conditions in order closes every loophole:

    ID_PREFIX = "recipe"
    
    
    def parse_id(recipe_id: str) -> Optional[int]:
        """Return n for an id of the exact form 'recipe<n>' (n >= 1, no leading zeros), else None."""
        # Reject non-strings and any string missing the exact lowercase "recipe" prefix.
        if not isinstance(recipe_id, str) or not recipe_id.startswith(ID_PREFIX):
            return None
    
        digits = recipe_id[len(ID_PREFIX):]
        # Check character-by-character before calling int(): bare int() would wrongly accept
        # spaces (" 7"), signs ("+7"), underscores ("1_0"), and non-ASCII digits ("١").
        if not digits or not digits.isascii() or not digits.isdigit():
            return None
    
        # Reject "recipe0" and leading zeros like "recipe01" so each recipe has one canonical ID.
        if digits[0] == "0":
            return None
    
        return int(digits)
    
    
    def name_key(name: str) -> str:
        """Return a canonical caseless key so 'RiSoTtO', 'risotto', and 'RISOTTO' map to the same string."""
        return name.casefold()
    

    Notice the order: not digits rejects "recipe" (empty suffix) before digits[0] is ever touched, digits.isascii() and digits.isdigit() restricts every character to '0'–'9', and digits[0] == "0" rules out both "recipe0" and "recipe01".

  5. Implement create and get with defensive copies

    In create, we check self.number_by_name before touching self.next_number so a rejected duplicate name never leaves a gap in the ID sequence. Both create and get copy ingredients and steps with list(...) so callers cannot mutate stored lists from the outside:

    class RecipeStore:
        def __init__(self) -> None:
            # Monotonic counter for the next issued ID; never decremented on failed create or delete.
            self.next_number: int = 1
            # Primary store: integer suffix -> Recipe, e.g. {1: Recipe("recipe1", "RiSoTtO", ["rice"], ["toast"])}
            self.recipes: Dict[int, Recipe] = {}
            # Secondary uniqueness index: case-folded name -> integer suffix, e.g. {"risotto": 1}
            self.number_by_name: Dict[str, int] = {}
    
        def create(self, name: str, ingredients: List[str], steps: List[str]) -> Optional[str]:
            # Phase 1: check case-insensitive name uniqueness before consuming an ID number.
            key = name_key(name)
            if key in self.number_by_name:
                return None
    
            # Phase 2: allocate the next sequential ID.
            number = self.next_number
            self.next_number += 1
            recipe_id = ID_PREFIX + str(number)
    
            # Phase 3: store defensive list copies so later caller edits cannot mutate internal state.
            stored_recipe = Recipe(
                id=recipe_id,
                name=name,
                ingredients=list(ingredients),
                steps=list(steps),
            )
            self.recipes[number] = stored_recipe
            self.number_by_name[key] = number
            return recipe_id
    
        def get(self, recipe_id: str) -> Optional[Recipe]:
            number = parse_id(recipe_id)
            if number is None or number not in self.recipes:
                return None
    
            stored = self.recipes[number]
            # Return a fresh Recipe and copied lists so callers cannot mutate the store behind its back.
            return Recipe(
                id=stored.id,
                name=stored.name,
                ingredients=list(stored.ingredients),
                steps=list(stored.steps),
            )
    
  6. Implement update and delete while keeping indexes in sync

    update validates all three failure rules before modifying anything: 1. recipe_id must parse cleanly and exist in self.recipes. 2. updated_recipe must be non-None and updated_recipe.id must equal recipe_id as an exact string (so "Recipe1" or "recipe2" cannot overwrite "recipe1"). 3. name_key(updated_recipe.name) must equal name_key(stored.name), which permits "RiSoTtO" -> "Risotto" while blocking "RiSoTtO" -> "Gnocchi".

    Because a case-only rename leaves name_key(...) identical, self.number_by_name already has the exact right key and number! Only delete needs to remove entries from both dictionaries:

        def update(self, recipe_id: str, updated_recipe: Recipe) -> bool:
            # Validate that recipe_id has valid syntax and currently exists in the store.
            number = parse_id(recipe_id)
            if number is None or number not in self.recipes:
                return False
    
            # Require an exact string match on ID (rejects None, "recipe2", "Recipe1", or "recipe01").
            if updated_recipe is None or updated_recipe.id != recipe_id:
                return False
    
            stored = self.recipes[number]
            # Allow only case changes to the name (e.g. "RiSoTtO" -> "Risotto"), blocking real renames.
            if name_key(updated_recipe.name) != name_key(stored.name):
                return False
    
            # Because the case-folded key did not change, self.number_by_name stays valid as-is.
            stored.name = updated_recipe.name
            stored.ingredients = list(updated_recipe.ingredients)
            stored.steps = list(updated_recipe.steps)
            return True
    
        def delete(self, recipe_id: str) -> bool:
            number = parse_id(recipe_id)
            if number is None or number not in self.recipes:
                return False
    
            # Remove from both dictionaries together so the deleted name becomes available again,
            # while leaving self.next_number untouched so deleted IDs are never reused.
            stored = self.recipes.pop(number)
            del self.number_by_name[name_key(stored.name)]
            return True
    
  7. Trace Example 1 and deletion step by step

    Walk through Example 1 followed by a delete-and-recreate cycle to verify every invariant on the counter and both dictionaries:

    Operation                                             Return      next_number  recipes                     number_by_name
    ----------------------------------------------------  ----------  -----------  --------------------------  ----------------------------
    create("RiSoTtO", ["arborio rice", ...], [...])       "recipe1"   2            {1: "RiSoTtO"}              {"risotto": 1}
    create("risotto", ["rice"], ["boil"])                 None        2            {1: "RiSoTtO"}              {"risotto": 1}  (rejected!)
    create("Chili", ["beans", "tomatoes"], ["simmer"])    "recipe2"   3            {1: "RiSoTtO", 2: "Chili"}  {"risotto": 1, "chili": 2}
    get("recipe01")                                       None        3            unchanged (leading zero rejected)
    update("recipe1", Recipe("recipe2", "RiSoTtO", ...))  False       3            unchanged (ID mismatch)
    update("recipe1", Recipe("recipe1", "Gnocchi", ...))  False       3            unchanged (real rename blocked)
    update("recipe1", Recipe("recipe1", "Risotto", ...))  True        3            {1: "Risotto", 2: "Chili"}  {"risotto": 1, "chili": 2}
    get("recipe1").name                                   "Risotto"   3            returns new casing "Risotto"
    delete("recipe1")                                     True        3            {2: "Chili"}                {"chili": 2}
    create("RISOTTO", ["rice"], ["stir"])                 "recipe3"   4            {2: "Chili", 3: "RISOTTO"}  {"chili": 2, "risotto": 3}
    
  8. Complete solution

    Put the helper functions, Recipe dataclass, and RecipeStore class together:

    from typing import Dict, List, Optional
    from dataclasses import dataclass
    
    ID_PREFIX = "recipe"
    
    
    @dataclass
    class Recipe:
        id: str
        name: str
        ingredients: List[str]
        steps: List[str]
    
    
    def parse_id(recipe_id: str) -> Optional[int]:
        """Return n for an id of the exact form 'recipe<n>' (n >= 1, no leading zeros), else None."""
        # Reject non-strings and any string missing the exact lowercase "recipe" prefix.
        if not isinstance(recipe_id, str) or not recipe_id.startswith(ID_PREFIX):
            return None
    
        digits = recipe_id[len(ID_PREFIX):]
        # Check character-by-character before calling int(): bare int() would wrongly accept
        # spaces (" 7"), signs ("+7"), underscores ("1_0"), and non-ASCII digits ("١").
        if not digits or not digits.isascii() or not digits.isdigit():
            return None
    
        # Reject "recipe0" and leading zeros like "recipe01" so each recipe has one canonical ID.
        if digits[0] == "0":
            return None
    
        return int(digits)
    
    
    def name_key(name: str) -> str:
        """Return a canonical caseless key so 'RiSoTtO', 'risotto', and 'RISOTTO' map to the same string."""
        return name.casefold()
    
    
    class RecipeStore:
        def __init__(self) -> None:
            # Monotonic counter for the next issued ID; never decremented on failed create or delete.
            self.next_number: int = 1
            # Primary store: integer suffix -> Recipe, e.g. {1: Recipe("recipe1", "RiSoTtO", ["rice"], ["toast"])}
            self.recipes: Dict[int, Recipe] = {}
            # Secondary uniqueness index: case-folded name -> integer suffix, e.g. {"risotto": 1}
            self.number_by_name: Dict[str, int] = {}
    
        def create(self, name: str, ingredients: List[str], steps: List[str]) -> Optional[str]:
            # Phase 1: check case-insensitive name uniqueness before consuming an ID number.
            key = name_key(name)
            if key in self.number_by_name:
                return None
    
            # Phase 2: allocate the next sequential ID.
            number = self.next_number
            self.next_number += 1
            recipe_id = ID_PREFIX + str(number)
    
            # Phase 3: store defensive list copies so later caller edits cannot mutate internal state.
            stored_recipe = Recipe(
                id=recipe_id,
                name=name,
                ingredients=list(ingredients),
                steps=list(steps),
            )
            self.recipes[number] = stored_recipe
            self.number_by_name[key] = number
            return recipe_id
    
        def get(self, recipe_id: str) -> Optional[Recipe]:
            number = parse_id(recipe_id)
            if number is None or number not in self.recipes:
                return None
    
            stored = self.recipes[number]
            # Return a fresh Recipe and copied lists so callers cannot mutate the store behind its back.
            return Recipe(
                id=stored.id,
                name=stored.name,
                ingredients=list(stored.ingredients),
                steps=list(stored.steps),
            )
    
        def update(self, recipe_id: str, updated_recipe: Recipe) -> bool:
            # Validate that recipe_id has valid syntax and currently exists in the store.
            number = parse_id(recipe_id)
            if number is None or number not in self.recipes:
                return False
    
            # Require an exact string match on ID (rejects None, "recipe2", "Recipe1", or "recipe01").
            if updated_recipe is None or updated_recipe.id != recipe_id:
                return False
    
            stored = self.recipes[number]
            # Allow only case changes to the name (e.g. "RiSoTtO" -> "Risotto"), blocking real renames.
            if name_key(updated_recipe.name) != name_key(stored.name):
                return False
    
            # Because the case-folded key did not change, self.number_by_name stays valid as-is.
            stored.name = updated_recipe.name
            stored.ingredients = list(updated_recipe.ingredients)
            stored.steps = list(updated_recipe.steps)
            return True
    
        def delete(self, recipe_id: str) -> bool:
            number = parse_id(recipe_id)
            if number is None or number not in self.recipes:
                return False
    
            # Remove from both dictionaries together so the deleted name becomes available again,
            # while leaving self.next_number untouched so deleted IDs are never reused.
            stored = self.recipes.pop(number)
            del self.number_by_name[name_key(stored.name)]
            return True
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of RecipeStore as a library desk that supports CRUD (Create, Read, Update, and Delete — the four basic operations of record storage) using two small index binders and a paper ticket dispenser:

  1. A numbered binder (recipes, a hash map / dictionary — a key-value table that finds, adds, or deletes an item by key in O(1) average time) maps each integer ticket number (1, 2, ...) to the full Recipe card with the author's exact capitalization (such as "RiSoTtO").
  2. A title binder (number_by_name) maps the case-folded recipe name (a canonical lowercase form, such as "risotto", used for case-insensitive comparison) to that same ticket number (1), letting the desk check instantaneously whether any capitalization of a name is already taken.
  3. A ticket dispenser (next_number) starts at 1 and only ever counts upward when a new recipe is accepted, so rejected duplicates never waste a number and deleted numbers are never handed to a different dish.

A naive implementation stores recipes in a single list and scans from start to finish on every call, which slows down linearly (O(N)) as the store grows to N recipes. Using only one dictionary also falls short: keying solely by ID still forces an O(N) scan across every recipe to check duplicate names during create, while keying solely by lowercase name forces an O(N) scan to look up "recipe42" during get, update, and delete. Maintaining two synchronized dictionaries gives O(1) average lookup by both ID and case-insensitive name, while defensive copies (duplicating mutable objects and lists on input and output) prevent callers from editing stored recipes behind the store's back.

Walk through 5 events on an empty store (next_number = 1, recipes = {}, number_by_name = {}):

  • create("RiSoTtO", ["arborio rice", "broth"], ["toast rice", "ladle broth"]) -> "risotto" is not in number_by_name, so ticket 1 is issued: recipes[1] = Recipe("recipe1", "RiSoTtO", ...), number_by_name["risotto"] = 1, next_number becomes 2, returns "recipe1".
  • create("risotto", ["rice"], ["boil"]) -> "risotto" is already in number_by_name, so create returns None right away and next_number stays 2.
  • update("recipe1", Recipe("recipe1", "Risotto", ["arborio rice", "broth", "parmesan"], ["toast rice", "ladle broth", "fold cheese"])) -> "recipe1" parses to 1, the IDs match, and "Risotto" case-folds to the same key "risotto", so recipes[1].name becomes "Risotto" while number_by_name["risotto"] = 1 needs no change; returns True.
  • delete("recipe1") -> pops 1 from recipes and deletes "risotto" from number_by_name while leaving next_number = 2; returns True.
  • create("RISOTTO", ["rice"], ["stir"]) -> "risotto" is free again, so it succeeds with the next unused ID "recipe2".

Complexity

  • Time: O(L) average per operation, where L is the size of the single recipe touched by that call (the length of recipe_id and name for validation, case folding, and hashing, plus the number of ingredients and steps list entries copied during create, get, and update; delete only parses recipe_id and hashes stored.name). Dictionary lookups, insertions, and deletions take O(1) average time, so runtime never grows with the total number of stored recipes N.
  • Space: O(S), where S is the total memory of all currently stored recipes (their strings and list elements). Each active recipe adds just one entry in recipes and one case-folded key plus integer in number_by_name, and delete frees both entries immediately.

Edge cases

  • Duplicate names in any capitalization: "RiSoTtO" blocks "risotto" and "RISOTTO", returning None without advancing next_number.
  • Deleted IDs stay retired, deleted names become reusable: after delete("recipe1") on "Waffles", get("recipe1") stays None forever, while create("WAFFLES", ...) succeeds under the next fresh ID ("recipe2").
  • Malformed ID strings: "", "recipe", "Recipe1", "recipe0", "recipe01", "recipe 1", "recipe+1", "recipe1_0", "recipe1a", and non-ASCII digits like "recipe١" all fail cleanly in get, update, and delete.
  • Mismatched or missing updated_recipe.id: passing None for updated_recipe, or passing Recipe("recipe2", ...) or Recipe("Recipe1", ...) to update("recipe1", ...), returns False and leaves the store untouched.
  • Zero-letter case change during update: updating "RiSoTtO" with "RiSoTtO" (identical casing) is valid and lets callers update ingredients and steps freely.
  • Whitespace counts as a real character change: "RiSoTtO " does not case-fold to "risotto", so update rightly rejects it as a rename.

Common mistakes

  • Calling int() directly on the ID suffix without character checks: Python's int() strips spaces and accepts +, -, underscores ("1_0" -> 10), and non-ASCII Unicode digits ("١" -> 1), allowing multiple malformed strings to alias "recipe1" or "recipe10".
  • Accepting "recipe0" or "recipe01": IDs start at 1 and have no leading zeros; failing to check digits[0] == "0" lets "recipe01" access "recipe1".
  • Incrementing next_number before checking duplicate names: doing the increment too early creates skipped numbers ("recipe1", then "recipe3") whenever a duplicate create fails.
  • Storing the lowercased name instead of the original name: overwrites "RiSoTtO" with "risotto", breaking the requirement that get preserves the stored casing.
  • Forgetting to remove the name from number_by_name on delete: leaves a ghost lock on "risotto" so that dish name can never be created again.
  • Returning internal Recipe objects or storing caller lists directly: without list(...) copies and a fresh Recipe in get, a caller running got.name = "Gnocchi" silently renames the stored recipe and desynchronizes number_by_name.

Alternative approaches

  • Dynamic array (List[Optional[Recipe]]) indexed by number - 1: appending on create and setting slots[number - 1] = None on delete gives exact worst-case O(1) lookup by number, at the cost of keeping one None reference slot per deleted recipe if deletions outnumber active recipes over a long-lived process.
  • Keying recipes by the validated ID string ("recipe1") instead of int: equally fast once parse_id validates the format, though storing integer keys avoids keeping a duplicate string key and makes sorting or range queries by creation order trivial.

Follow-up questions

  • How would you make RecipeStore thread-safe when concurrent callers invoke its methods simultaneously? Protect every public method (create, get, update, delete) with a single lock / mutex (a synchronization primitive ensuring only one thread executes a protected block of code at a time), such as Python's threading.Lock. That makes check-then-act sequences — like checking key in self.number_by_name and then inserting into both dictionaries — atomic so two threads cannot create "Risotto" and "RISOTTO" simultaneously or read half-updated state. Because get already returns a defensive copy while holding the lock, callers can safely inspect the returned Recipe after the lock is released.
  • How would update change if callers were permitted to rename a recipe to an entirely new title? First compute old_key = name_key(stored.name) and new_key = name_key(updated_recipe.name). If new_key != old_key, check whether new_key already exists in self.number_by_name (if so, return False because another recipe owns that title); otherwise del self.number_by_name[old_key] and set self.number_by_name[new_key] = number alongside updating stored.name. Updating both the record and the name index together preserves the invariant that recipes and number_by_name always agree.
  • How would you extend the store to support fast find_by_ingredient(ingredient) lookups? Add an inverted index (a lookup table mapping each attribute value, such as a case-folded ingredient string, to the set of record IDs containing it): recipes_by_ingredient: Dict[str, Set[int]]. On create, add number to the set for each unique case-folded ingredient; on delete, remove number from each stored ingredient's set (deleting empty sets to save memory); and on update, remove number from the old ingredients' sets and add it to the new ones. Lookups then run in O(K) time for K matching recipes instead of scanning all N recipes in the store.

Follow-up questions

Similar questions

More Circle interview questions

All 10 Circle questions →