Top 5 Delivery Routes by Fuel Efficiency
SQL & DataAuto-graded · 21 test casesLast updated
Tests aggregating trip data across two tables, guarding against division by zero, and ranking results with a deterministic tie-break.
Problem
You manage a logistics database tracking delivery runs across a fleet of vehicles. Your data lives in two collections: trips and service_records.
Data Shapes
trips — one entry per delivery run:
trip_id: unique identifier for the runvehicle_id: which vehicle made the rundistance_miles: kilometres driven (non-negative)fuel_consumed_gallons: fuel used (non-negative)
service_records — one entry per service event:
log_id: unique identifier for the service eventvehicle_id: which vehicle was servicedmaintenance_cost: cost of the service event
Task
Return the 5 most fuel-efficient vehicles that have at least one entry in service_records. Efficiency for a vehicle is defined as:
efficiency = total distance driven / total fuel consumed
where both totals are summed across all of that vehicle's trips.
Rules
- A vehicle is eligible only if its
vehicle_idappears at least once inservice_records, regardless of cost. - If a vehicle's total fuel consumption is
0or absent, its efficiency is0(do not divide by zero). - An eligible vehicle with no trips at all still appears in the output with efficiency
0. - Return each eligible vehicle as a dict with keys
vehicle_idandefficiency. - Sort results by
efficiencydescending. Break ties byvehicle_idascending. - Return at most 5 results; return fewer if fewer than 5 eligible vehicles exist.
Constraints
0 ≤ distance_miles,0 ≤ fuel_consumed_gallonsfor every trip row.- Either field may be
None; treatNoneas0. - A vehicle may have multiple service records; it still counts as one eligible vehicle.
- Do not average per-trip ratios. Compute the ratio of the summed totals.
Examples
Example 1
Input: top_5_efficient_routes([{'trip_id': 1, 'vehicle_id': 'A1', 'distance_miles': 100, 'fuel_consumed_gallons': 5}, {'trip_id': 2, 'vehicle_id': 'A1', 'distance_miles': 50, 'fuel_consumed_gallons': 5}, {'trip_id': 3, 'vehicle_id': 'B2', 'distance_miles': 200, 'fuel_consumed_gallons': 0}], [{'log_id': 101, 'vehicle_id': 'A1', 'maintenance_cost': 500}])
Output: [{'vehicle_id': 'A1', 'efficiency': 15}]
Hints
Hint 1
Build the set of eligible vehicles from service_records first, then look up trip totals for each one — not the other way around. This ensures vehicles with service records but no trips still appear in your output.
Hint 2
When computing efficiency, guard the division at the aggregate level: check whether total fuel is zero before dividing the total distance by it. Filtering out individual zero-fuel trips changes the numerator and gives the wrong answer.
Hint 3
Your sort key needs two levels: primary on efficiency (descending) and secondary on vehicle_id (ascending). Without the tie-break, results for vehicles with equal efficiency are non-deterministic.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three distinct steps: filter, aggregate, then rank.
1. Determine eligible vehicles
Build a set of vehicle_id values from service_records. Using a set automatically deduplicates vehicles that have multiple service entries. Only vehicles in this set can appear in the output.
2. Accumulate trip totals
Walk through every trip and add its distance and fuel to running totals keyed by vehicle_id. Use a defaultdict so that looking up a vehicle that never appears in trips silently returns [0, 0] — this is the Python equivalent of a SQL LEFT JOIN. Treat None values as 0 with or 0.
3. Compute efficiency and rank
Iterate over the eligible set (not the trip totals) to produce one result row per eligible vehicle. Dividing the aggregate totals rather than averaging per-trip ratios matches the problem definition exactly. Guard the single division: if total fuel is 0 (or the vehicle had no trips), assign efficiency 0.
Sort the result list with a two-level key: -efficiency for descending order, then vehicle_id for a deterministic alphabetical tie-break. Slice to at most 5 elements.
Why this is correct
- Every eligible vehicle gets exactly one output row because we iterate over the set.
- A vehicle with service records but zero trips appears with efficiency
0because thedefaultdictsupplies[0, 0]for missing keys. - No
ZeroDivisionErroris possible because the division is gated onfuelbeing truthy. - The sort key is a total order over unique vehicle IDs, so the top-5 selection is fully reproducible.
Complexity
Let T = number of trips, M = number of service records, V = number of distinct eligible vehicles.
- Time: O(T + M + V log V) — one pass each over trips and service records, plus one sort.
- Space: O(V + D) where D is the number of distinct vehicles appearing in trips.
Edge cases
| Situation | Behaviour |
|---|---|
| Vehicle has trips but no service record | Excluded from output |
| Eligible vehicle with no trips | Included, efficiency 0 |
| Total fuel = 0 across all trips | Efficiency 0 |
None distance or fuel on a trip | Treated as 0 |
| Vehicle with multiple service records | Counted once via the set |
| Fewer than 5 eligible vehicles | All of them returned |
| Many vehicles tied at efficiency 0 | Ordered by vehicle_id ascending |
Empty service_records | Empty list returned |
Reference solution
from typing import List, Dict
from collections import defaultdict
def top_5_efficient_routes(trips: List[Dict], service_records: List[Dict]) -> List[Dict]:
# Step 1: collect the set of vehicles that have been serviced at least once.
serviced = {record['vehicle_id'] for record in service_records}
# Step 2: accumulate total distance and total fuel per vehicle across all trips.
totals = defaultdict(lambda: [0, 0])
for trip in trips:
vid = trip['vehicle_id']
totals[vid][0] += trip['distance_miles'] or 0
totals[vid][1] += trip['fuel_consumed_gallons'] or 0
# Step 3: build results for every serviced vehicle.
# Iterating over `serviced` (not `totals`) acts like a LEFT JOIN:
# a serviced vehicle with no trips gets [0, 0] from the defaultdict.
results = []
for vid in serviced:
distance, fuel = totals[vid]
efficiency = distance / fuel if fuel else 0
results.append({'vehicle_id': vid, 'efficiency': efficiency})
# Step 4: sort descending by efficiency, ascending by vehicle_id for ties.
results.sort(key=lambda x: (-x['efficiency'], x['vehicle_id']))
return results[:5]