Retroactive Pay Ledger with Rate Changes and Shift Logging
Data Structure DesignModel answerLast updated
Design a class that records rate changes and shifts in any order, and reports total earnings under the current rate schedule using prefix sums and binary search.
Pay Ledger for a Single Worker
Design a class PayLedger that tracks one worker's pay. The worker's hourly rate changes over time, and shifts are reported after the fact, in any order. Rate changes can also arrive late, after shifts they affect have already been recorded.
Methods
set_rate(t, rate): from timet(inclusive) onward, the rate israte, until a later breakpoint sets a different one. Iftalready has a rate, the new value replaces it.add_shift(start, end): records a shift covering the half-open interval[start, end). Calls may come in any chronological order.total_pay(): returns the sum of pay for all recorded shifts under the current rate schedule.
Rules and constraints
t,start,endare non-negative integers.rateis a positive float.- Up to 10^5 total operations.
- A shift may span several rate periods, and may start or end in the middle of one.
- Time before the first rate breakpoint earns nothing.
- The last rate applies indefinitely.
- Every shift is paid on its own, so overlapping shifts are each paid in full.
- A shift with
start == endpays 0. A shift withend < startis invalid and should raise an error. - For consistency with the example, treat one time unit as one hour (pay = rate × duration). Isolate this in a single constant so it is easy to change.
Example
ledger = PayLedger()
ledger.set_rate(0, 10.0) # [0, 10) pays 10.0 per unit
ledger.set_rate(10, 20.0) # [10, inf) pays 20.0 per unit
ledger.add_shift(5, 15)
# [5, 10): 5 * 10.0 = 50.0
# [10, 15): 5 * 20.0 = 100.0
ledger.total_pay() # 150.0
What to deliver
Explain your design, state the assumptions you made about ambiguous points, give the time and space complexity of each method, and write the implementation. Discuss what happens when rate updates and total queries are heavily interleaved.
Hints
Hint 1
Pay for a shift is the integral of the rate over [start, end). Can you define a single function F(t) = pay accumulated from time 0 to t, so that a shift pays F(end) - F(start)?
Hint 2
F is piecewise linear between rate breakpoints. Sort the breakpoints and precompute the pay accumulated at each one, then use binary search to find which period t falls in.
Hint 3
Because a new rate can change the pay of shifts already logged, cached totals become stale on set_rate. Think about a dirty flag, and about how to avoid a full rebuild on every call if updates and queries alternate.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract
- Units. The example pays
5 * 10.0 = 50.0, so one time unit is one hour. I put the conversion in one constant (UNITS_PER_HOUR = 1); set it to 3600 if timestamps are real seconds. - Before the first rate: pays 0.
- Same-timestamp rate update: the latest write wins.
- Overlapping shifts: each is paid independently. I would state this out loud.
- Retroactive changes:
total_payalways reflects the current schedule, so a lateset_ratemust affect earlier shifts.
Core idea: cumulative pay function
Pay for a shift is the integral of the rate over [start, end). Define
F(t) = pay accumulated from time 0 to t under the current schedule.
Then pay(start, end) = F(end) - F(start), with no need to walk through each rate period the shift crosses.
F is piecewise linear. With sorted breakpoints t_0 < t_1 < ... < t_k and rates r_0 ... r_k:
prefix[0] = 0prefix[i] = prefix[i-1] + r_{i-1} * (t_i - t_{i-1})
To evaluate F(t):
i = bisect_right(times, t) - 1.- If
i < 0, return 0. - Otherwise return
prefix[i] + r_i * (t - t_i).
Each evaluation is O(log R), where R is the number of distinct breakpoints.
Check against the example: times = [0, 10], rates = [10, 20], prefix = [0, 100]. F(15) = 100 + 20*5 = 200, F(5) = 50, pay = 150.
Caching strategy
set_ratestores the rate in a dict and setsdirty = True, since any past shift may change.add_shiftappends the shift. If the cache is clean, it also adds the shift's pay to the running total in O(log R).total_payrebuilds the sorted breakpoints, prefix array and total only if dirty, then returns the cached total.
Why it is correct
- Within a period the rate is constant, so pay grows linearly and
prefix[i]is exactly the pay fromt_0tot_i. Fis continuous and equals 0 up tot_0, so differences ofFgive the exact integral regardless of how many periods a shift crosses or where it starts and ends.- Since the total is rebuilt from the current schedule whenever the schedule changes, input order does not matter.
Complexity
| Operation | Time |
|---|---|
set_rate | O(1) |
add_shift | O(1) dirty, O(log R) clean |
total_pay clean | O(1) |
total_pay dirty | O(R log R + S log R) |
Space is O(R + S), with S the number of shifts.
This is fine for 10^5 operations unless updates and queries strictly alternate. Then each query costs O(R + S) and the worst case approaches O(n^2).
Implementation
from bisect import bisect_right
class PayLedger:
UNITS_PER_HOUR = 1 # use 3600 for real seconds
def __init__(self):
self._rates = {}
self._shifts = []
self._times = []
self._rate_list = []
self._prefix = []
self._total = 0.0
self._dirty = True
def set_rate(self, t, rate):
self._rates[t] = rate
self._dirty = True
def add_shift(self, start, end):
if end < start:
raise ValueError("end must be >= start")
self._shifts.append((start, end))
if not self._dirty:
self._total += self._pay(start, end)
def total_pay(self):
if self._dirty:
self._rebuild()
return self._total
def _rebuild(self):
self._times = sorted(self._rates)
self._rate_list = [self._rates[t] for t in self._times]
n = len(self._times)
self._prefix = [0.0] * n
for i in range(1, n):
width = self._times[i] - self._times[i - 1]
self._prefix[i] = self._prefix[i - 1] + self._rate_list[i - 1] * width
self._dirty = False
self._total = sum(self._pay(s, e) for s, e in self._shifts)
def _cum(self, t):
i = bisect_right(self._times, t) - 1
if i < 0:
return 0.0
return self._prefix[i] + self._rate_list[i] * (t - self._times[i])
def _pay(self, s, e):
return (self._cum(e) - self._cum(s)) / self.UNITS_PER_HOUR
Edge cases
- Shift entirely before the first breakpoint: 0.
- Shift straddling the first breakpoint: only the part after it is paid.
- Zero-length shift: 0.
- Shift beyond the last breakpoint: the last rate continues.
- Overwriting a rate at an existing timestamp: handled by the dict.
- Calling
total_paywith no rates: returns 0.
Common mistakes
- Looping over every rate period for every shift, giving O(S * R).
- Forgetting that a late
set_rateinvalidates the running total. - Treating the shift as closed on the right, or double-counting at a boundary.
- Ignoring the hours-vs-seconds mismatch.
- Using floats for money. In production, use integer cents or
Decimal, since subtracting large prefix values loses precision.
Follow-up: heavily interleaved updates and queries
Rewrite the total as sum over t of rate(t) * c(t), where c(t) is the number of shifts covering time t.
- Coordinate-compress all timestamps (offline), or use a dynamic segment tree (online).
- Maintain
c(t)over elementary segments using a range-add structure that can also report a range sum of segment lengths times coverage. - A rate change at
tmodifies the rate over[t, next_breakpoint). The total changes by(new - old) * covered_length_in_that_range, which is one range query. - Logging a shift adds coverage and the total changes by the rate-weighted covered length over the range.
Both operations become O(log N), at the cost of a more complex structure. For many workers, key all state by worker id and shard on it, since workers are independent.