Restaurant Query and Order Analytics System
Data Structure DesignModel answerLast 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Strategy
This problem requires choosing appropriate data structures for different query patterns: linear filtering for price/distance optimization, time-indexed storage for range queries, and heaps for Top-K selection.
Clarifications and Assumptions
Before implementing, establish these details:
- Currency handling: Use integer cents to avoid floating-point errors
- Order fulfillment: A restaurant must have all requested items on its menu
- Nearest among valid: Distance is only relevant for restaurants that can actually serve the order
- Computed totals: Calculate order value from menu prices × quantities
- Time windows: Use
[start, end)to avoid boundary double-counting - Tie-breaking: Sort by restaurant/order ID for deterministic results
- Popularity metric: Count total units sold per item name across all restaurants
Core Approach
Part 1: Cheapest and Nearest Restaurant
For each restaurant, verify it can fulfill the order (menu contains all items), then compute:
- Cost: Sum of
menu_price[item] × quantityfor each item - Distance: Haversine formula from user coordinates to restaurant
Track the minimum across all valid restaurants. This requires O(R × m) where R is restaurant count and m is items per order—unavoidable since cost depends on the specific order composition.
Part 2: Time-Window Statistics
Maintain orders in timestamp-sorted order. Use binary search (bisect) to find the slice corresponding to [start, end):
bisect_left(timestamps, start)gives the first order ≥ startbisect_left(timestamps, end)gives the first order ≥ end- The slice between contains exactly the window
Precompute each order's total when ingesting, so statistics are simple aggregation over the slice.
Part 3: Top-K Rankings
For orders: Use heapq.nlargest(k, ...) on the window slice. This maintains a min-heap of size k, achieving O(w log k) instead of O(w log w) for full sorting.
For items: Aggregate quantities into a counter over the window, then extract the k largest entries. This is O(w × m + u log k) where u is distinct items.
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
| Find cheapest/nearest | O(R × m) | O(1) |
| Insert order | O(m) compute + O(log n) search + O(n) shift worst-case; O(m) if chronological | O(1) |
| Window statistics | O(log n + w) | O(1) |
| Top-K orders | O(log n + w log k) | O(k) |
| Top-K items | O(log n + w × m + u log k) | O(u) |
Storage: O(n × m) for all orders.
Correctness Reasoning
Feasibility filtering: Only restaurants with complete menu coverage are candidates, ensuring returned results are actually valid.
Binary search correctness: Sorted timestamps guarantee bisect finds exact window boundaries. Half-open intervals prevent overlap when windows are adjacent.
Heap correctness: nlargest keeps k maximum elements by discarding smaller ones incrementally, equivalent to sorting but more efficient.
Average edge case: Return 0 for empty windows instead of division by zero.
Edge Cases
- Empty desired order: Define behavior (reject or allow)
- No restaurant can serve the order: Return
None - Order references nonexistent restaurant or menu item: Raise error at ingestion
- Empty time window or
start ≥ end: Treat as empty k = 0ork > window_size: Handle gracefully- Out-of-order timestamps: Binary insertion handles this
- Duplicate timestamps: Bisect and half-open intervals remain correct
- Ties: Use stable secondary sort key
Implementation
import bisect
import heapq
import math
from collections import Counter
from typing import Dict, List, Optional, Tuple
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Calculate great-circle distance in kilometers."""
R = 6371.0
phi1, phi2 = math.radians(lat1), math.radians(lat2)
delta_phi = phi2 - phi1
delta_lambda = math.radians(lon2 - lon1)
a = (math.sin(delta_phi / 2) ** 2 +
math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2)
return 2 * R * math.asin(math.sqrt(a))
class Restaurant:
def __init__(self, id: str, lat: float, lon: float, menu: Dict[str, int]):
self.id = id
self.lat = lat
self.lon = lon
self.menu = menu # item_name -> price_cents
class Order:
def __init__(self, id: str, restaurant_id: str, items: Dict[str, int], timestamp: int):
self.id = id
self.restaurant_id = restaurant_id
self.items = items # item_name -> quantity
self.timestamp = timestamp
class DeliveryAnalytics:
def __init__(self, restaurants: List[Restaurant]):
self.restaurants = {r.id: r for r in restaurants}
self._order_timestamps = [] # sorted list
self._order_data = [] # parallel: (Order, precomputed_total_cents)
def _compute_order_cost(self, restaurant: Restaurant, items: Dict[str, int]) -> Optional[int]:
"""Return total cost in cents, or None if restaurant cannot fulfill."""
if not all(item in restaurant.menu for item in items):
return None
return sum(restaurant.menu[item] * qty for item, qty in items.items())
def find_cheapest_restaurant(self, desired_items: Dict[str, int]) -> Optional[Tuple[str, int]]:
"""Return (restaurant_id, total_cost) for cheapest valid option."""
best_cost = None
best_id = None
for restaurant in self.restaurants.values():
cost = self._compute_order_cost(restaurant, desired_items)
if cost is not None:
if best_cost is None or cost < best_cost or (cost == best_cost and restaurant.id < best_id):
best_cost = cost
best_id = restaurant.id
return (best_id, best_cost) if best_id else None
def find_nearest_restaurant(self, user_lat: float, user_lon: float,
desired_items: Dict[str, int]) -> Optional[Tuple[str, float]]:
"""Return (restaurant_id, distance_km) for nearest restaurant that can fulfill order."""
best_distance = None
best_id = None
for restaurant in self.restaurants.values():
if self._compute_order_cost(restaurant, desired_items) is None:
continue
distance = haversine_distance(user_lat, user_lon, restaurant.lat, restaurant.lon)
if best_distance is None or distance < best_distance or (distance == best_distance and restaurant.id < best_id):
best_distance = distance
best_id = restaurant.id
return (best_id, best_distance) if best_id else None
def add_order(self, order: Order):
"""Ingest an order (may arrive out of chronological sequence)."""
restaurant = self.restaurants.get(order.restaurant_id)
if not restaurant:
raise ValueError(f"Unknown restaurant: {order.restaurant_id}")
total = self._compute_order_cost(restaurant, order.items)
if total is None:
raise ValueError(f"Order {order.id} contains items not on menu")
# Binary insertion to maintain sorted order
idx = bisect.bisect_right(self._order_timestamps, order.timestamp)
self._order_timestamps.insert(idx, order.timestamp)
self._order_data.insert(idx, (order, total))
def window_statistics(self, start_time: int, end_time: int) -> Tuple[int, int, float]:
"""Return (total_revenue, order_count, average_order_value) for time window [start, end)."""
left = bisect.bisect_left(self._order_timestamps, start_time)
right = bisect.bisect_left(self._order_timestamps, end_time)
window_orders = self._order_data[left:right]
if not window_orders:
return (0, 0, 0.0)
total_revenue = sum(total for _, total in window_orders)
order_count = len(window_orders)
avg_value = total_revenue / order_count
return (total_revenue, order_count, avg_value)
def top_k_orders(self, start_time: int, end_time: int, k: int) -> List[Tuple[str, int]]:
"""Return list of (order_id, total_cost) for K highest-value orders in window."""
left = bisect.bisect_left(self._order_timestamps, start_time)
right = bisect.bisect_left(self._order_timestamps, end_time)
window_orders = self._order_data[left:right]
# Use negative order_id for deterministic tie-breaking (nlargest uses max-heap behavior)
candidates = [(-total, order.id, order, total) for order, total in window_orders]
top = heapq.nsmallest(k, candidates) # smallest negatives = largest positives
return [(order.id, total) for _, _, order, total in top]
def top_k_items(self, start_time: int, end_time: int, k: int) -> List[Tuple[str, int]]:
"""Return list of (item_name, total_quantity_sold) for K most popular items."""
left = bisect.bisect_left(self._order_timestamps, start_time)
right = bisect.bisect_left(self._order_timestamps, end_time)
item_counts = Counter()
for order, _ in self._order_data[left:right]:
for item, qty in order.items.items():
item_counts[item] += qty
# nlargest with tuple: primary by count descending, secondary by name ascending
top = heapq.nlargest(k, item_counts.items(), key=lambda x: (x[1], -ord(x[0][0]) if x[0] else 0))
return top
Common Mistakes
- Using floats for money (precision errors)
- Not filtering out restaurants that can't fulfill orders before finding nearest
- Sorting entire order history for each window query instead of binary search
- Full sorting for Top-K instead of heap-based selection
- Incorrect time window boundaries (inclusive on both ends causes double-counting)
- Not handling out-of-order event arrival
- Dividing by zero for average when window is empty