KatInterview

Build an In-Memory Meal Catalog with Search and Updates

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structuresstate-managementindexing

Last updated

Create a service that stores meal records with auto-incrementing IDs, normalized fields, atomic modifications, and filtered search with multiple sort orders.

Problem

Build an in-memory catalog system for managing meal records. The system must assign sequential IDs, normalize text fields, prevent partial updates on validation failures, and support filtered search with configurable ordering.

Core Requirements

ID Assignment and Field Normalization

  • Assign each new meal an integer ID, starting at 1 and incrementing by 1
  • Normalize ingredient and tag lists: remove leading/trailing whitespace, convert to lowercase, eliminate duplicates while maintaining the order of first appearances
  • Protect internal state from external mutations by creating independent copies of all input and output collections

Atomic Modification Guarantees

  • When updating a meal, either apply all changes or none at all
  • If any validation error occurs (negative preparation time, invalid meal ID, unrecognized field), leave the entire meal and all indexes unchanged

Filtered and Sorted Search

  • Filter by optional tag (case-insensitive match) and optional maximum preparation time (inclusive)
  • Support three sort modes:
    • "prep_time_asc": order by preparation time ascending, then by ID ascending
    • "prep_time_desc": order by preparation time descending, then by ID ascending
    • "title_asc": order by title alphabetically ascending, then by ID ascending
  • Return a list of meal IDs matching the filters in the specified order

Interface

class RecipeService:
    def __init__(self):
        pass

    def create_recipe(self, title: str, ingredients: list[str], tags: list[str], prep_time: int) -> int:
        """Store a new meal and return its assigned ID."""
        pass

    def get_recipe(self, recipe_id: int) -> dict | None:
        """Retrieve meal data as a dict with keys: 'id', 'title', 'ingredients', 'tags', 'prep_time'. 
        Returns None if the ID doesn't exist."""
        pass

    def update_recipe(self, recipe_id: int, updates: dict) -> bool:
        """Modify specified fields ('title', 'ingredients', 'tags', 'prep_time'). 
        Returns True on success, False on any validation failure."""
        pass

    def delete_recipe(self, recipe_id: int) -> bool:
        """Remove a meal by ID. Returns True if deleted, False if not found."""
        pass

    def search_recipes(self, tag: str | None = None, max_prep_time: int | None = None, 
                      sort_by: str = "prep_time_asc") -> list[int]:
        """Find meals matching the given criteria, sorted according to sort_by."""
        pass

Test Cases

service = RecipeService()
id1 = service.create_recipe("Omelette", ["Eggs", " Cheese ", "eggs"], ["Breakfast", " FAST "], 15)
# id1 == 1
# Stored ingredients: ["eggs", "cheese"]
# Stored tags: ["breakfast", "fast"]

id2 = service.create_recipe("Smoothie", ["banana", "milk"], ["breakfast"], 5)
# id2 == 2

service.search_recipes(tag="breakfast", max_prep_time=20, sort_by="prep_time_asc")
# Returns: [2, 1] (prep_time 5 before 15)

service.update_recipe(1, {"prep_time": -10})
# Returns: False (negative time rejected; meal unchanged)

service.delete_recipe(2)
# Returns: True

service.search_recipes(tag="breakfast")
# Returns: [1]

Constraints

  • Preparation time must be non-negative for valid records
  • Titles must be non-empty
  • At most 2 × 10^4 total operations
  • At most 5,000 meals stored simultaneously

Hints

Hint 1

Build a helper function to normalize string lists once and reuse it for both creation and updates.

Hint 2

Use an inverted index mapping each tag to the set of meal IDs that contain it to avoid scanning all meals on every search.

Hint 3

For atomic updates, validate all changes in local variables before modifying any shared state or indexes.