KatInterview

In-Memory Payroll Tracker with Partial Settlement

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designtime-intervalsmoney-arithmetic

Last updated

Build an object-oriented service to log driver work intervals, compute wages, and process payments while preventing double-pay and handling overlaps.

You're building a payroll computation engine for gig workers. The system must track work sessions, calculate compensation, and process wage settlements without double-paying.

Implement an in-memory service supporting these operations:

  1. add_driver(driver_id, usd_hourly_rate) — Register a worker with their hourly compensation rate
  2. record_delivery(driver_id, start_time, end_time) — Log a completed work session with start and end timestamps
  3. get_total_cost() — Return total accumulated labor costs across all workers and sessions
  4. pay_up_to(pay_time) — Mark all work completed before the given timestamp as paid
  5. get_total_cost_unpaid() — Return remaining wages that haven't been settled

Requirements and constraints:

  • Times are integer Unix timestamps (seconds since epoch, UTC)
  • Work sessions last between 1 second and 3 hours
  • A worker cannot have overlapping sessions (cannot work two jobs simultaneously)
  • Sessions ending exactly when another begins are allowed (no gap between consecutive work)
  • The pay_up_to operation must be idempotent: calling it multiple times with the same timestamp should not pay twice
  • If a session spans the payment cutoff time, settle the portion before the cutoff
  • Sessions may be recorded after a payment has already run (late entries)
  • Avoid floating-point arithmetic for money calculations

Your solution should address:

  • How you store workers, sessions, and payment state
  • Your strategy for precise money calculations
  • How you prevent double-payment with repeated or overlapping pay runs
  • How you handle sessions that cross payment boundaries
  • Time complexity of each operation
  • What changes would be needed for a production database-backed system

Hints

Hint 1

Store monetary amounts as integer cents to avoid floating-point errors; compute cent-seconds (rate_cents × duration_seconds) and divide by 3600 only when reporting.

Hint 2

Track how much of each session has been settled using a 'paid_until' marker that advances monotonically; use a priority queue to efficiently find unsettled work.

Hint 3

Adjacent sessions (end1 == start2) don't overlap, but intersecting intervals do; validate new sessions against existing ones sorted by start time.