Calculate Worker Pay with Bonus Time Periods
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Tests interval merging, overlap calculation, and time-based pay aggregation with capped rate multipliers.
You are implementing payroll calculations for a gig work platform.
Given a list of work records for one worker, calculate the total amount the worker should be paid.
Each work record is a dictionary containing:
order_id: a unique string identifierstatus: either"delivered"or"canceled"start_time: work start time, an integer representing minutes since midnightend_time: work end time, an integer representing minutes since midnighthourly_rate: the worker's base hourly rate for that work (dollars per hour)
You are also given:
canceled_pay: a fixed dollar amount paid for each canceled work orderbonus_periods: a list of time intervals[start, end)during which delivered work earns bonus pay at double the normal rate
Payment Rules:
- A delivered order pays the worker based on work duration and the hourly rate.
- Any portion of a delivered order that falls within a bonus period should be paid at double the hourly rate.
- Any portion that does not overlap a bonus period should be paid at the normal hourly rate.
- If multiple bonus periods overlap each other, the worker still receives at most double pay for any given minute (not triple or higher).
- A canceled order pays only the fixed
canceled_payamount; do not apply hourly calculations or bonus pay. - All time intervals use half-open semantics:
[start, end)includesstartbut excludesend.
Return the worker's total pay as a float.
Constraints:
- 0 ≤ number of orders ≤ 1000
- 0 ≤ number of bonus periods ≤ 500
- 0 ≤ start_time < end_time ≤ 1440 for valid intervals
- 0 ≤ hourly_rate ≤ 200
- 0 ≤ canceled_pay ≤ 100
- Bonus periods may overlap, be nested, or be unsorted
- Work intervals may have start_time ≥ end_time (treat as zero duration)
Examples
Example 1
Input: calculate_worker_pay([{'order_id': 'A', 'status': 'delivered', 'start_time': 60, 'end_time': 120, 'hourly_rate': 30}, {'order_id': 'B', 'status': 'canceled', 'start_time': 130, 'end_time': 160, 'hourly_rate': 30}, {'order_id': 'C', 'status': 'delivered', 'start_time': 150, 'end_time': 210, 'hourly_rate': 24}], 5, [[90, 150], [180, 240]])
Output: 86
Hints
Hint 1
Overlapping bonus periods must not stack beyond 2x pay. How can you consolidate them into non-overlapping intervals first?
Hint 2
Double pay means the worker earns the base rate plus one additional copy of the base rate for bonus minutes. Can you express total pay without splitting the work into separate segments?
Hint 3
Use the standard half-open interval overlap formula: max(0, min(end1, end2) - max(start1, start2))
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is handling overlapping bonus periods correctly. Rule 4 states that overlapping periods must not stack beyond 2x pay. The cleanest solution is to merge all bonus periods into disjoint intervals before calculating any pay.
Algorithm:
-
Merge bonus periods: Sort the periods by start time, then merge any that overlap or touch. After merging, each minute is covered by at most one interval, so we can never accidentally count it twice.
-
Process each order:
- If the order is canceled, add the fixed
canceled_payand skip hourly calculations. - If the order is delivered, compute:
duration= total minutes worked (clamped to zero if end ≤ start)bonus_minutes= total overlap between the order interval[start, end)and all merged bonus periods
- If the order is canceled, add the fixed
-
Calculate pay: For a delivered order, pay equals
rate × (duration + bonus_minutes) / 60. This works because double pay means earning the base rate once for every minute, plus an additional copy of the base rate for each bonus minute.
Why this is correct:
- Interval merging prevents stacking: Once merged, bonus periods are pairwise disjoint. Summing the order's overlap with each period counts every bonus minute exactly once.
- Half-open overlap formula: Two intervals
[a, b)and[c, d)overlap for exactlymax(0, min(b, d) - max(a, c))minutes. This correctly returns 0 for adjacent intervals that only touch at a boundary. - Early termination: Since merged intervals are sorted, once we encounter a bonus period starting at or after the order's end time, all subsequent periods can be skipped.
Complexity:
- Time: O(B log B + B) to sort and merge bonus periods, where B is the number of bonus periods. Then O(N × B) to process N orders against B merged intervals. Overall O(B log B + N × B).
- Space: O(B) for the merged intervals.
Edge cases handled:
- Overlapping or nested bonus periods are merged into one.
- Adjacent periods
[90, 120)and[120, 150)are also merged (safe, does not change coverage). - Empty or inverted intervals (start ≥ end) are skipped.
- Orders with zero or negative duration contribute zero pay.
- Canceled orders inside bonus periods still pay only the fixed amount.
- Orders that touch but don't overlap a bonus period (order ends at 90, period starts at 90) correctly have zero overlap due to half-open semantics.
from typing import Dict, List
def calculate_worker_pay(orders: List[Dict], canceled_pay: float, bonus_periods: List[List[int]]) -> float:
# Merge bonus periods into non-overlapping intervals
# This ensures no minute is counted as "bonus" more than once
merged = []
for start, end in sorted(bonus_periods):
if start >= end:
continue # Skip empty intervals
if merged and start <= merged[-1][1]:
# Overlaps or touches the last merged interval
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
total = 0.0
for order in orders:
# Canceled orders receive only the fixed compensation
if order["status"] == "canceled":
total += canceled_pay
continue
start = order["start_time"]
end = order["end_time"]
rate = order["hourly_rate"]
duration = max(0, end - start)
# Calculate how many minutes overlap with bonus periods
bonus_minutes = 0
for window_start, window_end in merged:
if window_end <= start:
continue # Window ends before order starts
if window_start >= end:
break # Window starts after order ends; all later windows do too
bonus_minutes += max(0, min(end, window_end) - max(start, window_start))
# Pay: base rate for all minutes + extra base rate for bonus minutes
total += rate * (duration + bonus_minutes) / 60
return total