KatInterview

Restaurant Query and Order Analytics System

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structuresalgorithmstime-series

Last updated

Design data structures and algorithms to query restaurants by price and distance, then compute order statistics and rankings over time windows.

You're building an analytics backend for a meal delivery service. You have access to restaurant data (each restaurant has an identifier, coordinates, and a menu mapping dish names to prices in cents) and a stream of completed orders (each specifies which restaurant, which dishes with quantities, and when it occurred).

Design and implement a system supporting these operations:

1. Restaurant selection queries

Given a customer's desired dishes (with quantities) and their coordinates:

  • Find which restaurant can fulfill this order at minimum cost
  • Find which restaurant that can fulfill this order is geographically closest

2. Aggregate statistics over a time range

For all orders within a specified time interval [start_time, end_time):

  • Calculate total revenue (sum of all order values)
  • Count how many orders occurred
  • Compute average order value

3. Rankings over a time range

For the same time interval, determine:

  • The K most expensive orders
  • The K most popular menu items (by total quantity sold)

Input format:

  • Restaurant locations are latitude/longitude pairs; use haversine distance
  • Prices are integers (cents)
  • Timestamps are integers (Unix epoch seconds)
  • Time windows use half-open intervals: [start, end)

Requirements:

  • A restaurant can only fulfill an order if its menu contains every requested item
  • Handle orders arriving out of chronological sequence
  • Break ties consistently (by identifier for restaurants, by order ID or item name for rankings)

What to provide:

  • Data structure choices and their rationale
  • Algorithm for each operation with time/space complexity
  • Edge case handling (empty orders, no valid restaurant, empty time windows, ties)
  • Implementation in Python

Hints

Hint 1

For finding cheapest/nearest, consider that each query depends on a specific order's items—can you precompute anything useful?

Hint 2

Time-window queries need fast range lookup. What data structure helps you quickly locate all orders in [start, end)?

Hint 3

For Top-K problems, do you need to fully sort, or is there a more efficient bounded structure?