Food Platform Analytics: Basket Pricing and Order Metrics
SQL & DataModel answerLast updated
Design functions to find the best-priced restaurant for a shopping cart, calculate revenue metrics over time windows, and identify top orders and items.
You're building analytics for a food delivery platform with restaurant data and order history.
Part 1: Best Restaurant for a Cart
Given:
- A customer's coordinates (latitude, longitude)
- A list of restaurants, each with location and a menu (item name → price in cents)
- A shopping cart specifying items and quantities
Find which restaurant can fulfill the cart at the lowest total cost. If multiple restaurants tie on price, choose the geographically closest. If there's still a tie, choose the one with the lexicographically smallest restaurant ID.
Return the restaurant ID, or None if no restaurant stocks all requested items.
Part 2: Time-Windowed Revenue Metrics
Given a collection of orders (each with a timestamp and line items), support queries that compute for any time range [start, end):
- Total revenue (sum of all order values)
- Number of orders
- Average order value (or
Nonefor empty windows)
Multiple queries may request overlapping or different windows. Design for efficiency when the same data is queried repeatedly with different boundaries.
Part 3: Top-K Rankings
For a given time window:
- Return the K highest-value orders (by total price)
- Return the K best-selling items (by units sold)
Define clear tie-breaking rules. Discuss how you'd maintain these rankings in real-time as new orders arrive, and analyze the time complexity of updates and queries.
Implement working code with clear function signatures and handle edge cases.
Hints
Hint 1
For geographic distance, the haversine formula gives great-circle distance between coordinates. Consider what precision is meaningful for ranking.
Hint 2
Store orders sorted by time. Precomputed prefix sums enable O(log n) window queries via binary search.
Hint 3
For top-K with changing counts, a min-heap of size K works for one-time queries. For continuous updates, consider maintaining a sorted structure or using a hash map plus periodic re-sorting.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires combining data structures for filtering, aggregation, and ranking. The key is choosing the right tool for each query pattern while clearly defining edge cases.
Design Decisions
Money as integers. Represent all prices in cents to avoid floating-point comparison issues. When comparing totals for ties, integer arithmetic ensures exact equality checks.
Time windows are half-open [start, end). This convention prevents double-counting when adjacent windows are computed.
Distance calculation. Use haversine distance (great-circle) in kilometers for geographic ranking. Round to a reasonable precision (e.g., 1 meter) to prevent spurious tie-breaks from float imprecision. Real routing distance would require external services.
Deterministic tie-breaking. Always include a stable final tiebreaker (typically ID) so results are reproducible across runs.
Part 1: Finding the Cheapest Restaurant
Algorithm:
- For each restaurant, check if its menu contains every item in the cart
- If eligible, compute
total_cost = Σ(price × quantity) - Calculate distance from customer to restaurant using haversine
- Track the best restaurant using tuple comparison:
(total_cost, distance, restaurant_id)
Tuple lexicographic ordering naturally encodes the priority: lowest cost first, then nearest, then smallest ID.
Complexity: O(R × I) where R is the number of restaurants and I is the number of cart items. Space is O(1) additional.
Edge cases:
- No restaurant has all items: return
None - Empty cart: all restaurants cost 0, so return the nearest
- Invalid quantities (≤ 0): reject with an error
Part 2: Windowed Revenue Metrics
Static data approach:
- Sort orders by timestamp
- Build a prefix sum array:
prefix[i] = sum of first i order totals - For window
[start, end):- Binary search to find indices
left = bisect_left(start)andright = bisect_left(end) - Revenue =
prefix[right] - prefix[left] - Count =
right - left - AOV = revenue / count (or
Noneif count is 0)
- Binary search to find indices
Each query takes O(log N) time, making multiple overlapping windows efficient.
Handling late arrivals: If orders arrive out of sequence, insert them in sorted position and mark the prefix array dirty. Rebuild it lazily on the next query (O(N) worst case, amortized across many queries).
For high-frequency updates, use a Fenwick tree (binary indexed tree) on compressed timestamps, giving O(log N) for both updates and queries.
Complexity: O(N log N) preprocessing, O(log N) per query, O(1) space per order.
Part 3: Top-K Rankings
Top-K Orders by Value
Single window query:
- Slice orders in the time range
- Use a heap-based selection:
heapq.nsmallest(k, orders, key=lambda o: (-o.total, o.timestamp, o.id))
The key encodes: highest total first (negated for max-heap behavior), earliest timestamp for ties, smallest ID as final tiebreaker.
Complexity: O(M log k) where M is orders in the window.
Top-K Items by Units Sold
Single window query:
- Iterate through all order line items in the window
- Aggregate quantities into a hash map:
item_id → total_units - Select top K using:
heapq.nsmallest(k, items, key=lambda x: (-units[x], x))
Complexity: O(L) to aggregate (L = total line items), then O(U log k) to select (U = distinct items).
Real-Time Sliding Window
For continuous queries like "top items in the last 5 minutes":
Approach:
- Maintain a deque of
(timestamp, item_id, quantity)tuples - Keep a
Countertracking current units per item - On new order: append to deque, increment counter
- Periodically: pop expired entries from deque front, decrement counter
- On query: run heap selection over counter (O(U log k))
Each event is processed exactly twice (add and remove), giving O(1) amortized per event.
Alternative for query-heavy workloads:
Maintain a balanced tree (e.g., SortedList) keyed by (-units, item_id). Each count change requires removing and re-inserting in O(log U), but top-K queries become O(k).
Common mistake: Using a "lazy deletion heap" where you push updates without removing stale entries. This works when values only increase, but for items that may decrease (e.g., returns, cancellations), the heap fills with obsolete entries and must be periodically rebuilt.
Edge Cases Summary
- Part 1: Restaurants missing items, zero-quantity cart items, identical prices at same location
- Part 2: Empty windows (return count=0, revenue=0, AOV=None), orders exactly at boundary timestamps, duplicate timestamps
- Part 3: k exceeds available items/orders (return all), k ≤ 0 (return empty list), multiple orders with identical totals
Implementation Sketch
import math
import bisect
import heapq
from collections import Counter, deque
from typing import Optional
# Part 1
def haversine_km(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth radius in km
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = phi2 - phi1
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi/2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda/2)**2
return 2 * R * math.asin(math.sqrt(a))
def find_best_restaurant(customer_lat, customer_lon, restaurants, cart):
best = None
for restaurant in restaurants:
# Check if restaurant has all items
if not all(item in restaurant.menu for item in cart):
continue
total = sum(restaurant.menu[item] * qty for item, qty in cart.items())
dist = round(haversine_km(customer_lat, customer_lon,
restaurant.lat, restaurant.lon), 3)
candidate = (total, dist, restaurant.id)
if best is None or candidate < best:
best = candidate
return best[2] if best else None
# Part 2
class MetricsEngine:
def __init__(self):
self.timestamps = []
self.orders = []
self.prefix_sums = [0]
def add_order(self, order):
self.timestamps.append(order.timestamp)
self.orders.append(order)
self.prefix_sums.append(self.prefix_sums[-1] + order.total)
def query_window(self, start, end):
left = bisect.bisect_left(self.timestamps, start)
right = bisect.bisect_left(self.timestamps, end)
revenue = self.prefix_sums[right] - self.prefix_sums[left]
count = right - left
aov = revenue / count if count > 0 else None
return {'revenue': revenue, 'count': count, 'aov': aov}
# Part 3
def top_k_orders(orders, k):
return heapq.nsmallest(k, orders,
key=lambda o: (-o.total, o.timestamp, o.id))
def top_k_items(orders, k):
units = Counter()
for order in orders:
for item_id, qty, _ in order.items:
units[item_id] += qty
return heapq.nsmallest(k, units.keys(),
key=lambda item: (-units[item], item))
This solution demonstrates practical data manipulation skills: choosing appropriate data structures (sorted lists with binary search, prefix sums, heaps, hash maps), handling edge cases explicitly, and analyzing trade-offs between preprocessing and query time.