Carrier Defect Metrics and High-Risk Shipping Routes
SQL & DataAuto-graded · 14 test casesLast updated
Aggregating shipment quality metrics by carrier and time period, computing period-over-period changes, and ranking routes by defect frequency.
You are analyzing logistics data to track shipment quality across carriers and identify problematic shipping routes.
You are given two data structures:
shipments: A list of dictionaries, each representing a shipment with fields:
shipment_id(int): unique identifierorder_id(int): associated ordership_date(str): date the shipment departed, in ISO format (YYYY-MM-DD)carrier(str): shipping company (e.g., "UPS", "FedEx", "USPS")origin(str): departure location codedestination(str): arrival location codestatus(str): current status
defects: A list of dictionaries, each representing a quality issue with fields:
defect_id(int): unique identifiershipment_id(int): references a shipmentdefect_type(str): category of issue (e.g., "Damaged", "Lost", "LateDelivery")defect_reported_date(str): date the issue was reported, in ISO format
reference_date (str): the analysis anchor date in ISO format.
Your task is to produce a dictionary with two keys:
-
"weekly": A list of weekly defect rate records for each carrier, covering shipments that departed in the 30-day window ending onreference_date(inclusive). Each record contains:carrier(str)week_start(str): the Monday starting that ISO week, in ISO formatdefect_rate(float): total defects divided by total shipments for that carrier in that weekwow_pct_change(float or None): percentage change from the previous week's rate for this carrier, orNoneif there is no previous week or the previous rate was zero
Sort by carrier (ascending), then by week_start (ascending).
-
"top_lanes": A list of up to 3 origin-destination pairs with the highest count of "Damaged" defects reported in the 90-day window ending onreference_date(inclusive). Each record contains:origin(str)destination(str)damaged_defect_count(int): number of Damaged defects on this route
Sort by count (descending), then by origin (ascending), then by destination (ascending). Return at most 3 records.
Important details:
- The 30-day window for weekly analysis includes all shipments where
reference_date - 29 days ≤ ship_date ≤ reference_date. - The 90-day window for lane analysis includes all defects where
reference_date - 89 days ≤ defect_reported_date ≤ reference_date. - A shipment with multiple defects contributes all of them to the defect count (the rate can exceed 1.0).
- Each shipment is counted exactly once in the denominator for its carrier and week, regardless of how many defects it has.
- The week starts on Monday. Use ISO week calculation (Monday = day 0).
- For week-over-week change, compare each week to the immediately preceding week in the sorted list for that carrier, not necessarily the previous calendar week.
- If the previous week's rate is zero,
wow_pct_changeshould beNoneto avoid division by zero. - Defects linked to shipments not present in the shipments list should be ignored.
Constraints:
- 0 ≤ len(shipments) ≤ 10,000
- 0 ≤ len(defects) ≤ 50,000
- All dates are valid ISO format strings
shipment_idvalues in defects may or may not match shipments- Carrier, origin, and destination strings are non-empty and at most 50 characters
- Defect types are non-empty strings
Examples
Example 1
Input: compute_carrier_metrics([{'shipment_id': 1001, 'order_id': 5001, 'ship_date': '2023-09-04', 'carrier': 'UPS', 'origin': 'SEA', 'destination': 'NYC', 'status': 'Delivered'}, {'shipment_id': 1002, 'order_id': 5002, 'ship_date': '2023-09-05', 'carrier': 'UPS', 'origin': 'SEA', 'destination': 'CHI', 'status': 'Delivered'}, {'shipment_id': 1003, 'order_id': 5003, 'ship_date': '2023-09-11', 'carrier': 'UPS', 'origin': 'LAX', 'destination': 'NYC', 'status': 'Delivered'}, {'shipment_id': 1004, 'order_id': 5004, 'ship_date': '2023-09-12', 'carrier': 'FedEx', 'origin': 'LAX', 'destination': 'CHI', 'status': 'Delivered'}], [{'defect_id': 1, 'shipment_id': 1001, 'defect_type': 'Damaged', 'defect_reported_date': '2023-09-06'}, {'defect_id': 2, 'shipment_id': 1001, 'defect_type': 'LateDelivery', 'defect_reported_date': '2023-09-07'}, {'defect_id': 3, 'shipment_id': 1003, 'defect_type': 'Damaged', 'defect_reported_date': '2023-09-13'}, {'defect_id': 4, 'shipment_id': 1004, 'defect_type': 'Lost', 'defect_reported_date': '2023-09-14'}], '2023-09-30')
Output: {'weekly': [{'carrier': 'FedEx', 'week_start': '2023-09-11', 'defect_rate': 1, 'wow_pct_change': None}, {'carrier': 'UPS', 'week_start': '2023-09-04', 'defect_rate': 1, 'wow_pct_change': None}, {'carrier': 'UPS', 'week_start': '2023-09-11', 'defect_rate': 1, 'wow_pct_change': 0}], 'top_lanes': [{'origin': 'LAX', 'destination': 'NYC', 'damaged_defect_count': 1}, {'origin': 'SEA', 'destination': 'NYC', 'damaged_defect_count': 1}]}
Example 2
Input: compute_carrier_metrics([{'shipment_id': 1, 'order_id': 1, 'ship_date': '2024-01-15', 'carrier': 'USPS', 'origin': 'A', 'destination': 'B', 'status': 'Delivered'}, {'shipment_id': 2, 'order_id': 2, 'ship_date': '2024-01-16', 'carrier': 'FedEx', 'origin': 'A', 'destination': 'C', 'status': 'Delivered'}, {'shipment_id': 3, 'order_id': 3, 'ship_date': '2024-02-05', 'carrier': 'USPS', 'origin': 'A', 'destination': 'B', 'status': 'Delivered'}], [{'defect_id': 1, 'shipment_id': 1, 'defect_type': 'Damaged', 'defect_reported_date': '2024-01-16'}, {'defect_id': 2, 'shipment_id': 3, 'defect_type': 'Damaged', 'defect_reported_date': '2024-02-06'}], '2024-02-10')
Output: {'weekly': [{'carrier': 'FedEx', 'week_start': '2024-01-15', 'defect_rate': 0, 'wow_pct_change': None}, {'carrier': 'USPS', 'week_start': '2024-01-15', 'defect_rate': 1, 'wow_pct_change': None}, {'carrier': 'USPS', 'week_start': '2024-02-05', 'defect_rate': 1, 'wow_pct_change': 0}], 'top_lanes': [{'origin': 'A', 'destination': 'B', 'damaged_defect_count': 2}]}
Hints
Hint 1
Build an index of defects per shipment first to avoid double-counting shipments with multiple defects in your denominator
Hint 2
Use ISO week calculation: the week starts on Monday, so subtract the weekday number from the ship date to find the Monday of that week
Hint 3
When computing week-over-week change, compare consecutive weeks in your sorted data per carrier, not calendar weeks—gaps are allowed
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires three distinct aggregations:
- Weekly defect rates per carrier over a 30-day window anchored on ship dates
- Week-over-week percentage changes comparing consecutive weeks for each carrier
- Top shipping routes ranked by Damaged defect frequency over a 90-day window
The key challenge is avoiding a classic join trap: if you naively join shipments to defects and then count rows, a shipment with two defects gets counted twice in your denominator, artificially inflating the defect rate.
Solution strategy:
First, build an index that maps each shipment ID to its total defect count. This pre-aggregation ensures we can later add defects to the numerator without duplicating shipments in the denominator.
Next, iterate through shipments in the 30-day window (where ship_date falls between reference_date - 29 and reference_date, inclusive). For each shipment:
- Compute the ISO week by finding the Monday of that week (subtract the weekday number from the date)
- Increment both the shipment count and defect count for the
(carrier, week_start)bucket - The defect count comes from our pre-built index
After bucketing, compute the defect rate for each carrier-week pair as total_defects / total_shipments.
For week-over-week changes, organize records by carrier and sort by week within each carrier. Walk through each carrier's weeks sequentially, computing (current_rate - previous_rate) / previous_rate * 100. The first week for any carrier has no prior comparison, so its change is None. If the previous rate was zero, also return None to avoid division by zero.
For the lane analysis, filter defects to those with defect_type == "Damaged" and defect_reported_date in the 90-day window (between reference_date - 89 and reference_date, inclusive). Join each defect to its shipment to extract the origin and destination, then count occurrences per lane. Sort by count descending, then by origin ascending, then by destination ascending as a tiebreaker. Take the top 3.
Why this works:
- Pre-aggregating defects per shipment guarantees each shipment is counted exactly once in the denominator
- All defects on a shipment still contribute to the numerator (rates above 1.0 are valid)
- Week-over-week logic follows a simple sequential scan pattern, matching LAG window function semantics
- Lane ranking uses defect-reported date as the filter criterion, correctly attributing each Damaged defect to exactly one route
Complexity:
Let S = number of shipments, D = number of defects, W = number of distinct (carrier, week) pairs, and L = number of distinct lanes.
- Time: O(S + D + W log W + L log L). Building indices and buckets is linear; sorting weekly records and lanes dominates.
- Space: O(S + D + W + L) for the lookup structures and output lists.
Code:
from datetime import date, timedelta
from collections import defaultdict
from typing import List, Dict
def compute_carrier_metrics(shipments: List[Dict], defects: List[Dict], reference_date: str) -> Dict:
ref = date.fromisoformat(reference_date)
window_30_start = ref - timedelta(days=29)
window_90_start = ref - timedelta(days=89)
# Index shipments and aggregate defects per shipment
shipment_lookup = {}
defect_counts_per_shipment = defaultdict(int)
for s in shipments:
shipment_lookup[s["shipment_id"]] = s
for d in defects:
sid = d["shipment_id"]
defect_counts_per_shipment[sid] += 1
# Build weekly aggregates for carriers
weekly_buckets = defaultdict(lambda: [0, 0]) # [shipment_count, defect_count]
for s in shipments:
ship_day = date.fromisoformat(s["ship_date"])
if window_30_start <= ship_day <= ref:
# Find the Monday of this week
monday = ship_day - timedelta(days=ship_day.weekday())
bucket_key = (s["carrier"], monday)
weekly_buckets[bucket_key][0] += 1
weekly_buckets[bucket_key][1] += defect_counts_per_shipment[s["shipment_id"]]
# Organize by carrier for sequential week-over-week calculation
carrier_weeks = defaultdict(list)
for (carrier, monday), (ship_count, defect_count) in weekly_buckets.items():
rate = defect_count / ship_count
carrier_weeks[carrier].append((monday, rate))
# Compute week-over-week changes
weekly_output = []
for carrier in sorted(carrier_weeks):
week_records = sorted(carrier_weeks[carrier])
prior_rate = None
for monday, rate in week_records:
if prior_rate is None or prior_rate == 0:
change_pct = None
else:
change_pct = (rate - prior_rate) / prior_rate * 100.0
weekly_output.append({
"carrier": carrier,
"week_start": monday.isoformat(),
"defect_rate": rate,
"wow_pct_change": change_pct,
})
prior_rate = rate
# Count Damaged defects per lane in 90-day window
lane_damage_counts = defaultdict(int)
for d in defects:
if d["defect_type"] != "Damaged":
continue
reported = date.fromisoformat(d["defect_reported_date"])
if not (window_90_start <= reported <= ref):
continue
s = shipment_lookup.get(d["shipment_id"])
if s is not None:
lane_key = (s["origin"], s["destination"])
lane_damage_counts[lane_key] += 1
# Sort and take top 3 lanes
top_lanes_output = [
{
"origin": origin,
"destination": destination,
"damaged_defect_count": count
}
for (origin, destination), count in sorted(
lane_damage_counts.items(),
key=lambda item: (-item[1], item[0][0], item[0][1])
)[:3]
]
return {
"weekly": weekly_output,
"top_lanes": top_lanes_output
}