Worker Pay Rate Ledger with Interval Cost Queries
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests piecewise-constant function integration, lazy evaluation, and interval clipping inside a simulated in-memory billing system.
Problem Statement
You are building an in-memory earnings tracker for a gig-worker platform. Each worker has an hourly pay rate (in cents) that can be updated at any point in time. Jobs are logged as half-open time intervals [start_time, end_time) measured in seconds. Your system must answer cost and payout queries that respect the exact rate in effect during each second of a job.
Implement a function that processes a sequence of operations given as two parallel lists — operations (strings) and arguments (lists of values) — and returns a list of results, one per operation.
The four supported operations are:
set_rate
Arguments: [worker_id: str, timestamp: int, cents_per_hour: int]
Records that worker_id earns cents_per_hour cents per hour starting at timestamp (inclusive). This rate stays in effect until a later rate is registered for the same worker. Multiple calls for the same worker and the same timestamp are allowed; the last call wins. Rate updates may arrive in any order.
Returns: None
record_delivery
Arguments: [job_id: str, worker_id: str, start_time: int, end_time: int]
Registers a job completed by worker_id over the interval [start_time, end_time), where start_time < end_time. Each job_id is unique across all calls.
Returns: None
get_delivery_cost
Arguments: [job_id: str]
Returns the total cost in cents for the given job. If the job spans multiple rate periods, compute the cost of each segment separately as duration_seconds * rate / 3600 (unrounded), sum all segments, then round the total using math.floor(total + 0.5).
Returns: int
get_courier_payout
Arguments: [worker_id: str, start_time: int, end_time: int]
Returns the total earnings in cents for worker_id across all jobs that overlap with the query window [start_time, end_time). For a job that only partially falls inside the window, count only the overlapping portion. A job whose endpoint exactly equals the window's start (or whose start equals the window's end) does not overlap.
Sum all unrounded segment costs across all overlapping (clipped) jobs, then apply a single math.floor(total + 0.5) to produce the final result.
Returns: int
Constraints
- All timestamps and time values are non-negative integers:
0 ≤ timestamp,start_time,end_time ≤ 10^9 - For every logged job,
start_time < end_time - Every job's
start_timeis greater than or equal to the earliestset_ratetimestamp recorded for that worker (so there is always a rate in effect at the job's start) - At most
10^4total calls across all operations - Each
job_idis unique - Jobs belonging to the same worker do not overlap each other
cents_per_hour ≥ 0
Examples
Example 1
Input: worker_pay_ledger(['set_rate', 'set_rate', 'record_delivery', 'get_delivery_cost', 'get_courier_payout'], [['C1', 0, 1800], ['C1', 3600, 2400], ['D1', 'C1', 1800, 5400], ['D1'], ['C1', 3600, 7200]])
Output: [None, None, None, 2100, 1200]
Hints
Hint 1
Store each worker's rate history as a dict mapping timestamp to rate. Sorting the timestamps at query time handles out-of-order arrivals without needing to keep them sorted on insert.
Hint 2
Don't compute a job's cost inside record_delivery. A set_rate call arriving later can still affect a rate that falls inside an already-logged job, so evaluate lazily at query time.
Hint 3
For get_courier_payout, clip each job to the query window first (overlap_start = max(window_start, job_start), overlap_end = min(window_end, job_end)), then price the clipped interval with the same segment-walking routine. Round the grand total once at the end, not per job.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: piecewise-constant integration
A worker's pay rate is a step function of time. The cost of any interval [a, b) is the integral of that step function divided by 3600 — the sum of duration * rate / 3600 over each contiguous sub-interval where the rate is constant. The problem reduces to computing that integral efficiently.
Data structures
Three dicts carry all state:
rates[worker_id]maps each change timestamp to the rate that takes effect at that moment.jobs[job_id]stores(worker_id, start, end)for each logged job.worker_jobs[worker_id]is the list of job IDs belonging to that worker, needed when iterating during a payout query.
Why evaluation is lazy
Cost is computed at query time, not at record_delivery time. A set_rate call can arrive after a job has already been logged, with a timestamp that falls inside that job's interval. Deferring evaluation means the cost always reflects the full, current rate history — no cache invalidation needed.
Walking the rate segments
Given an interval [start, end) for a worker:
- Sort the worker's rate-change timestamps.
- Use
bisect_right(times, start) - 1to find the index of the largest timestamp≤ start. That is the rate in effect atstart. The constraint guarantees this index is never −1. - Walk forward: each segment runs from
currenttomin(end, next_change_timestamp). Accumulateduration * rate / 3600for each segment, then advance.
The segments partition [start, end) exactly — no gaps, no overlaps.
Payout via clipping
For get_courier_payout(worker_id, window_start, window_end), iterate over the worker's jobs and clip each one to the query window:
overlap_start = max(window_start, job_start)
overlap_end = min(window_end, job_end)
If overlap_start < overlap_end the job contributes; price the clipped interval with the same segment_cost routine.
Rounding rule
Sum all unrounded segment costs first, then apply math.floor(total + 0.5) exactly once. For get_courier_payout the single rounding is over the grand total across all clipped jobs, not per job. Rounding per job would accumulate error.
Worked example
set_rate("C1", 0, 1800) # 1800 c/hr from t=0
set_rate("C1", 3600, 2400) # 2400 c/hr from t=3600
record_delivery("D1","C1",1800,5400)
get_delivery_cost("D1"):
segment [1800, 3600): 1800s * 1800/3600 = 900.0
segment [3600, 5400): 1800s * 2400/3600 = 1200.0
floor(2100.0 + 0.5) = 2100
get_courier_payout("C1", 3600, 7200):
D1 clipped to [3600, 5400): 1800s * 2400/3600 = 1200.0
floor(1200.0 + 0.5) = 1200
Complexity
| Operation | Time | Space |
|---|---|---|
set_rate | O(1) | O(1) per call |
record_delivery | O(1) | O(1) per call |
get_delivery_cost | O(K log K + S) | O(K) for the sorted list |
get_courier_payout | O(D · (K log K + S)) | O(K) |
K = number of rate changes for the worker, S = number of rate-period segments the interval spans, D = number of jobs for the worker. With at most 10^4 total calls this is well within limits.
Edge cases
- Out-of-order
set_ratecalls — sorting at query time handles them automatically. - Duplicate timestamp — the later
set_ratecall overwrites the dict entry; the last value wins. set_rateafterrecord_delivery— lazy evaluation picks it up with no extra work.- Job entirely in one rate period — the loop runs a single iteration.
- Job starts exactly on a change timestamp —
bisect_rightplaces the cursor to the right of that timestamp, soidxlands on the new rate, which is correct (rates are inclusive at their timestamp). - Window touches a job only at an endpoint —
overlap_start == overlap_end, so the job is skipped and contributes nothing. - Worker with no jobs, or no overlap at all —
floor(0.0 + 0.5) = 0.
Reference solution
import math
from bisect import bisect_right
from typing import List, Optional
def worker_pay_ledger(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
rates = {} # worker_id -> {timestamp: cents_per_hour}
jobs = {} # job_id -> (worker_id, start_time, end_time)
worker_jobs = {} # worker_id -> [job_id, ...]
results = []
def segment_cost(worker_id: str, start: int, end: int) -> float:
"""Unrounded cost in cents for the interval [start, end)."""
if start >= end:
return 0.0
changes = rates[worker_id]
times = sorted(changes)
idx = bisect_right(times, start) - 1
total = 0.0
current = start
while current < end:
next_time = times[idx + 1] if idx + 1 < len(times) else end
segment_end = min(end, next_time)
total += (segment_end - current) * changes[times[idx]] / 3600
current = segment_end
idx += 1
return total
for operation, args in zip(operations, arguments):
if operation == 'set_rate':
worker_id, timestamp, cents_per_hour = args
if worker_id not in rates:
rates[worker_id] = {}
rates[worker_id][timestamp] = cents_per_hour
results.append(None)
elif operation == 'record_delivery':
job_id, worker_id, start_time, end_time = args
jobs[job_id] = (worker_id, start_time, end_time)
worker_jobs.setdefault(worker_id, []).append(job_id)
results.append(None)
elif operation == 'get_delivery_cost':
job_id = args[0]
worker_id, start_time, end_time = jobs[job_id]
results.append(math.floor(segment_cost(worker_id, start_time, end_time) + 0.5))
elif operation == 'get_courier_payout':
worker_id, start_time, end_time = args
total = 0.0
for job_id in worker_jobs.get(worker_id, []):
_, job_start, job_end = jobs[job_id]
overlap_start = max(start_time, job_start)
overlap_end = min(end_time, job_end)
if overlap_start < overlap_end:
total += segment_cost(worker_id, overlap_start, overlap_end)
results.append(math.floor(total + 0.5))
else:
raise ValueError('Unknown operation: ' + operation)
return results