KatInterview

Retroactive Pay Ledger with Rate Changes and Shift Logging

Data Structure DesignModel answer
HardModel answerData Structure Designdesignprefix-sumbinary-search

Last 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

  1. set_rate(t, rate): from time t (inclusive) onward, the rate is rate, until a later breakpoint sets a different one. If t already has a rate, the new value replaces it.
  2. add_shift(start, end): records a shift covering the half-open interval [start, end). Calls may come in any chronological order.
  3. total_pay(): returns the sum of pay for all recorded shifts under the current rate schedule.

Rules and constraints

  • t, start, end are non-negative integers.
  • rate is 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 == end pays 0. A shift with end < start is 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.