KatInterview

Food Platform Analytics: Basket Pricing and Order Metrics

SQL & DataModel answer
MediumModel answerSQL & Datadata-structuresaggregationwindow-queries

Last 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 None for 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.