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 dishingredients(List[str]): ordered ingredient stringssteps(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) -> booldelete(recipe_id: str) -> bool
Behavioral Rules
- Monotonic ID allocation: Accepted
createcalls receive"recipe1","recipe2","recipe3", ... in strict creation order starting at1. A rejectedcreatenever advances the counter, and numbers from deleted recipes are never issued again. - Strict ID parsing:
get,update, anddeleteaccept a stringrecipe_idand extract its numeric suffix. Only the exact lowercase prefix"recipe"followed by an ASCII base-10 integern >= 1with 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 causegetto returnNoneandupdate/deleteto returnFalse. - Caseless title uniqueness: At most one active recipe may hold a given title when letter case is ignored (for instance,
"RiSoTtO"and"risotto"conflict). Ifcreatereceives a conflicting title, it leaves the store unchanged and returnsNone. Deleting a recipe releases its title for future creations. - Stored casing preservation:
getreturns the recipe using the exact capitalization currently stored ("RiSoTtO"stays"RiSoTtO"). - Update validation & case-only title edits:
update(recipe_id, updated_recipe)replacesname,ingredients, andstepsand returnsTrueif and only if:recipe_idis well-formed and currently stored,updated_recipeis non-Noneandupdated_recipe.id == recipe_id(exact string match), andupdated_recipe.namediffers from the stored recipe'snameat most in letter casing (e.g.,"RiSoTtO"to"Risotto"is valid, whereas"RiSoTtO"to"Gnocchi"fails). When a case-only title update succeeds, subsequentgetcalls return the newly saved casing; otherwiseupdatereturnsFalsewithout altering stored state.
- State isolation: Mutating caller lists passed into
create/update, or mutating aRecipereturned byget, 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 returnsNonewithout 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, andupdatefails whenupdated_recipe.id("recipe2") does not matchrecipe_id("recipe1").- Deleting
"recipe1"frees the title"Waffles"so"WAFFLES"can be created under the next fresh ID"recipe2".
Constraints
- Up to
10^5total calls acrosscreate,get,update, anddelete. - 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
Understand the contract and edge rules
We need to build an in-memory
RecipeStoresupporting CRUD operations (Create, Read, Update, and Delete) overRecipe(id, name, ingredients, steps)records:create(name, ingredients, steps) -> Optional[str]: stores a new recipe and returns"recipe1","recipe2", ..., orNoneif the title is already taken (ignoring letter case).get(recipe_id) -> Optional[Recipe]: looks up a recipe by ID string, returningNoneif 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.idmatchesrecipe_idcharacter-for-character, andupdated_recipe.namediffers from the stored name only in letter case.delete(recipe_id) -> bool: removes an existing recipe and returnsTrue, or returnsFalseif the ID is invalid or missing.
Before writing code, settle four subtle edge rules from the specification and
starter.py:- Failed creates do not waste numbers: if
"RiSoTtO"already exists,create("risotto", ...)returnsNoneand the next valid recipe still gets"recipe2", not"recipe3". - 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. - 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. - Defensive copies in and out: copying lists on
create,get, andupdateprevents outside code from mutating aRecipeoringredientslist behind the store's back.
Why a plain list is too slow
The simplest possible store keeps a single Python list of
Recipeobjects:create: loop through every stored recipe, compareexisting.name.lower() == name.lower(), and append if no match is found.get,update,delete: loop through the list untilexisting.id == recipe_id.
If the store holds
Nrecipes, every single method scans up toNentries (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 (Pythondict).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.recipesmaps the parsed integer suffix (1,2, ...) to the storedRecipeobject, preserving the exact capitalization ("RiSoTtO") thatgetmust return.self.number_by_namemaps the case-folded name ("risotto") to that recipe's integer suffix (1), lettingcreatecheck inO(1)average time whether any casing of that name is already active.self.next_numberstarts at1and increments only whencreatesucceeds.
We normalize names using Python's
str.casefold(), which is a stricter version ofstr.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").Parse and validate recipe IDs strictly
get,update, anddeleteall receive a string such as"recipe2"and must extract the positive integer2. Slicing after"recipe"and callingint(digits)directly is a classic trap because Python'sint()quietly accepts whitespace (" 7"), signs ("+7"), underscores ("1_0"->10), and leading zeros ("01"->1), whilestr.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 digitsrejects"recipe"(empty suffix) beforedigits[0]is ever touched,digits.isascii() and digits.isdigit()restricts every character to'0'–'9', anddigits[0] == "0"rules out both"recipe0"and"recipe01".Implement create and get with defensive copies
In
create, we checkself.number_by_namebefore touchingself.next_numberso a rejected duplicate name never leaves a gap in the ID sequence. Bothcreateandgetcopyingredientsandstepswithlist(...)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), )Implement update and delete while keeping indexes in sync
updatevalidates all three failure rules before modifying anything: 1.recipe_idmust parse cleanly and exist inself.recipes. 2.updated_recipemust be non-Noneandupdated_recipe.idmust equalrecipe_idas an exact string (so"Recipe1"or"recipe2"cannot overwrite"recipe1"). 3.name_key(updated_recipe.name)must equalname_key(stored.name), which permits"RiSoTtO" -> "Risotto"while blocking"RiSoTtO" -> "Gnocchi".Because a case-only rename leaves
name_key(...)identical,self.number_by_namealready has the exact right key and number! Onlydeleteneeds 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 TrueTrace 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}Complete solution
Put the helper functions,
Recipedataclass, andRecipeStoreclass 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:
- A numbered binder (
recipes, a hash map / dictionary — a key-value table that finds, adds, or deletes an item by key inO(1)average time) maps each integer ticket number (1,2, ...) to the fullRecipecard with the author's exact capitalization (such as"RiSoTtO"). - 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. - A ticket dispenser (
next_number) starts at1and 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 innumber_by_name, so ticket1is issued:recipes[1] = Recipe("recipe1", "RiSoTtO", ...),number_by_name["risotto"] = 1,next_numberbecomes2, returns"recipe1".create("risotto", ["rice"], ["boil"])->"risotto"is already innumber_by_name, socreatereturnsNoneright away andnext_numberstays2.update("recipe1", Recipe("recipe1", "Risotto", ["arborio rice", "broth", "parmesan"], ["toast rice", "ladle broth", "fold cheese"]))->"recipe1"parses to1, the IDs match, and"Risotto"case-folds to the same key"risotto", sorecipes[1].namebecomes"Risotto"whilenumber_by_name["risotto"] = 1needs no change; returnsTrue.delete("recipe1")-> pops1fromrecipesand deletes"risotto"fromnumber_by_namewhile leavingnext_number = 2; returnsTrue.create("RISOTTO", ["rice"], ["stir"])->"risotto"is free again, so it succeeds with the next unused ID"recipe2".
Complexity
- Time:
O(L)average per operation, whereLis the size of the single recipe touched by that call (the length ofrecipe_idandnamefor validation, case folding, and hashing, plus the number ofingredientsandstepslist entries copied duringcreate,get, andupdate;deleteonly parsesrecipe_idand hashesstored.name). Dictionary lookups, insertions, and deletions takeO(1)average time, so runtime never grows with the total number of stored recipesN. - Space:
O(S), whereSis the total memory of all currently stored recipes (their strings and list elements). Each active recipe adds just one entry inrecipesand one case-folded key plus integer innumber_by_name, anddeletefrees both entries immediately.
Edge cases
- Duplicate names in any capitalization:
"RiSoTtO"blocks"risotto"and"RISOTTO", returningNonewithout advancingnext_number. - Deleted IDs stay retired, deleted names become reusable: after
delete("recipe1")on"Waffles",get("recipe1")staysNoneforever, whilecreate("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 inget,update, anddelete. - Mismatched or missing
updated_recipe.id: passingNoneforupdated_recipe, or passingRecipe("recipe2", ...)orRecipe("Recipe1", ...)toupdate("recipe1", ...), returnsFalseand leaves the store untouched. - Zero-letter case change during
update: updating"RiSoTtO"with"RiSoTtO"(identical casing) is valid and lets callers updateingredientsandstepsfreely. - Whitespace counts as a real character change:
"RiSoTtO "does not case-fold to"risotto", soupdaterightly rejects it as a rename.
Common mistakes
- Calling
int()directly on the ID suffix without character checks: Python'sint()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 at1and have no leading zeros; failing to checkdigits[0] == "0"lets"recipe01"access"recipe1". - Incrementing
next_numberbefore checking duplicate names: doing the increment too early creates skipped numbers ("recipe1", then"recipe3") whenever a duplicatecreatefails. - Storing the lowercased name instead of the original name: overwrites
"RiSoTtO"with"risotto", breaking the requirement thatgetpreserves the stored casing. - Forgetting to remove the name from
number_by_nameondelete: leaves a ghost lock on"risotto"so that dish name can never be created again. - Returning internal
Recipeobjects or storing caller lists directly: withoutlist(...)copies and a freshRecipeinget, a caller runninggot.name = "Gnocchi"silently renames the stored recipe and desynchronizesnumber_by_name.
Alternative approaches
- Dynamic array (
List[Optional[Recipe]]) indexed bynumber - 1: appending oncreateand settingslots[number - 1] = Noneondeletegives exact worst-caseO(1)lookup by number, at the cost of keeping oneNonereference slot per deleted recipe if deletions outnumber active recipes over a long-lived process. - Keying
recipesby the validated ID string ("recipe1") instead ofint: equally fast onceparse_idvalidates 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
RecipeStorethread-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'sthreading.Lock. That makes check-then-act sequences — like checkingkey in self.number_by_nameand then inserting into both dictionaries — atomic so two threads cannot create"Risotto"and"RISOTTO"simultaneously or read half-updated state. Becausegetalready returns a defensive copy while holding the lock, callers can safely inspect the returnedRecipeafter the lock is released. - How would
updatechange if callers were permitted to rename a recipe to an entirely new title? First computeold_key = name_key(stored.name)andnew_key = name_key(updated_recipe.name). Ifnew_key != old_key, check whethernew_keyalready exists inself.number_by_name(if so, returnFalsebecause another recipe owns that title); otherwisedel self.number_by_name[old_key]and setself.number_by_name[new_key] = numberalongside updatingstored.name. Updating both the record and the name index together preserves the invariant thatrecipesandnumber_by_namealways 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]]. Oncreate, addnumberto the set for each unique case-folded ingredient; ondelete, removenumberfrom each stored ingredient's set (deleting empty sets to save memory); and onupdate, removenumberfrom the old ingredients' sets and add it to the new ones. Lookups then run inO(K)time forKmatching recipes instead of scanning allNrecipes in the store.
Follow-up questions
- How would you make `RecipeStore` thread-safe when concurrent callers invoke its methods simultaneously?
- How would `update` change if callers were permitted to rename a recipe to an entirely new title?
- How would you extend the store to support fast `find_by_ingredient(ingredient)` lookups?
Similar questions
- Four-Stage Account Ledger and Payment Engine
- Minimum-Cost Flight Route With Departure Window
- Recovering Lost Time During a Pair-Programming Session
- Scheduled Payment Execution and Outgoing Reporting System
- Flight Fare Aggregation and Search System
- Versioned In-Memory Store with Field TTL and Snapshots
More Circle interview questions
- Recovering Lost Time During a Pair-Programming Session Medium
- Scheduled Payment Execution and Outgoing Reporting System Hard
- Flight Fare Aggregation and Search System Hard Pro
- Versioned In-Memory Store with Field TTL and Snapshots Hard Pro
- Four-Stage Account Ledger and Payment Engine Medium Pro
- Minimum-Cost Flight Route With Departure Window Medium Pro
- Ledger Service With Activity Leaderboard and Time-Limited Holds Medium Pro
- Tracing and Cutting Duplicate HTTP Calls in curl Clients Medium Pro
- Half-Open UTC Timestamp Filtering on Flight Bookings Medium Pro