In-Memory Payroll Tracker with Partial Settlement
Data Structure DesignModel answerLast 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:
- add_driver(driver_id, usd_hourly_rate) — Register a worker with their hourly compensation rate
- record_delivery(driver_id, start_time, end_time) — Log a completed work session with start and end timestamps
- get_total_cost() — Return total accumulated labor costs across all workers and sessions
- pay_up_to(pay_time) — Mark all work completed before the given timestamp as paid
- 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_tooperation 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to design stateful systems with careful accounting. The core challenges are money precision, idempotent payments, and partial settlement of work sessions.
Key Design Decisions
1. Money Representation
Never use floating-point for currency. Store rates as integer cents per hour. For each work interval, compute the exact cost as:
cost_in_cent_seconds = rate_cents_per_hour × duration_seconds
This product is exact. Only convert to dollars when reporting:
dollars = Decimal(cent_seconds) / 360000
Round to cents using banker's rounding (ROUND_HALF_EVEN). This ensures total_cost = paid + unpaid holds exactly.
2. Time Intervals
Use half-open intervals [start, end) where start is inclusive and end is exclusive. This makes adjacent sessions non-overlapping: a session ending at T and another starting at T are legal and back-to-back.
To detect overlaps, maintain each worker's sessions in sorted order by start time. A new interval [s, e) overlaps existing intervals if:
- The previous interval's end > s, OR
- The next interval's start < e
Use binary search for O(log n) insertion point lookup.
3. Settlement State
Each session tracks settled_until, initially equal to start_time. This marks how much of the session has been paid.
Store unsettled sessions in a min-heap ordered by settled_until. When pay_up_to(t) runs:
- Extract all sessions where
settled_until < t - For each, pay from
settled_untiltomin(end_time, t) - Update
settled_untiltomin(end_time, t) - If
settled_until < end_time, reinsert into heap
This design guarantees:
- Idempotency: Calling
pay_up_to(t)again finds no sessions withsettled_until < t, so pays nothing - Monotonicity:
settled_untilonly increases; each second is paid exactly once - Partial settlement: Sessions spanning the cutoff are split naturally
- Late entries: Back-dated sessions enter the heap and settle on the next payment run
4. Overlap Prevention
Maintain each worker's sessions sorted by start time. Before inserting, verify the new interval doesn't intersect existing ones. Adjacent intervals (sharing a boundary point) are explicitly allowed.
Data Structures
class Driver:
driver_id: str
rate_cents_per_hour: int
sessions: list[tuple[int, int]] # sorted (start, end) pairs
class Session:
session_id: int
driver_id: str
start: int
end: int
rate_cents_per_hour: int # snapshot at creation
settled_until: int # advances as payments run
class PayrollService:
drivers: dict[str, Driver]
sessions: dict[int, Session]
unsettled_heap: list[tuple[int, int]] # (settled_until, session_id)
total_cent_seconds: int
paid_cent_seconds: int
Implementation
import heapq
from bisect import bisect_left
from dataclasses import dataclass, field
from decimal import Decimal, ROUND_HALF_EVEN
MAX_SESSION_DURATION = 3 * 3600
@dataclass
class Driver:
driver_id: str
rate_cents_per_hour: int
sessions: list = field(default_factory=list)
@dataclass
class Session:
session_id: int
driver_id: str
start: int
end: int
rate_cents_per_hour: int
settled_until: int
def compute_cost(self, from_time: int, to_time: int) -> int:
return self.rate_cents_per_hour * (to_time - from_time)
class PayrollService:
def __init__(self):
self.drivers = {}
self.sessions = {}
self.unsettled_heap = []
self.next_session_id = 1
self.total_cent_seconds = 0
self.paid_cent_seconds = 0
def add_driver(self, driver_id: str, usd_hourly_rate: float):
if driver_id in self.drivers:
raise ValueError(f"Driver {driver_id} already exists")
rate_cents = int(Decimal(str(usd_hourly_rate)) * 100)
if rate_cents < 0:
raise ValueError("Rate must be non-negative")
self.drivers[driver_id] = Driver(driver_id, rate_cents)
def record_delivery(self, driver_id: str, start_time: int, end_time: int) -> int:
if driver_id not in self.drivers:
raise KeyError(f"Unknown driver: {driver_id}")
driver = self.drivers[driver_id]
if start_time >= end_time:
raise ValueError("Start must be before end")
if end_time - start_time > MAX_SESSION_DURATION:
raise ValueError("Session exceeds maximum duration")
# Check for overlaps using binary search
sessions = driver.sessions
idx = bisect_left(sessions, (start_time, start_time))
if idx > 0 and sessions[idx - 1][1] > start_time:
raise ValueError("Overlaps with existing session")
if idx < len(sessions) and sessions[idx][0] < end_time:
raise ValueError("Overlaps with existing session")
sessions.insert(idx, (start_time, end_time))
# Create session record
session_id = self.next_session_id
self.next_session_id += 1
session = Session(
session_id=session_id,
driver_id=driver_id,
start=start_time,
end=end_time,
rate_cents_per_hour=driver.rate_cents_per_hour,
settled_until=start_time
)
self.sessions[session_id] = session
heapq.heappush(self.unsettled_heap, (start_time, session_id))
cost = session.compute_cost(start_time, end_time)
self.total_cent_seconds += cost
return session_id
def pay_up_to(self, pay_time: int):
pending = []
while self.unsettled_heap and self.unsettled_heap[0][0] < pay_time:
_, session_id = heapq.heappop(self.unsettled_heap)
session = self.sessions[session_id]
pay_until = min(session.end, pay_time)
amount = session.compute_cost(session.settled_until, pay_until)
self.paid_cent_seconds += amount
session.settled_until = pay_until
if session.settled_until < session.end:
pending.append((session.settled_until, session_id))
for item in pending:
heapq.heappush(self.unsettled_heap, item)
def get_total_cost(self) -> Decimal:
return (Decimal(self.total_cent_seconds) / 360000).quantize(
Decimal("0.01"), rounding=ROUND_HALF_EVEN)
def get_total_cost_unpaid(self) -> Decimal:
unpaid = self.total_cent_seconds - self.paid_cent_seconds
return (Decimal(unpaid) / 360000).quantize(
Decimal("0.01"), rounding=ROUND_HALF_EVEN)
Complexity Analysis
| Operation | Time Complexity | Space |
|---|---|---|
add_driver | O(1) | O(1) per driver |
record_delivery | O(log n + n) worst case, O(log n) with balanced tree | O(1) per session |
get_total_cost | O(1) | — |
pay_up_to | O(k log N) amortized where k = sessions settled | — |
get_total_cost_unpaid | O(1) | — |
The O(n) factor in record_delivery comes from list insertion after binary search. A balanced tree (TreeMap, SortedList) makes this O(log n).
Production Considerations
Database schema:
driverstable: id, rate_cents_per_hoursessionstable: id, driver_id, start_time, end_time, rate_snapshot, settled_until, statuspayment_runstable: run_id, cutoff_time, total_amount- Index on
(driver_id, start_time)andsettled_until
Concurrency: Use row-level locks or optimistic locking (version columns) to prevent race conditions during payment processing.
Audit trail: Never delete or rewrite settled sessions. Model corrections as compensating ledger entries.
Rate changes: Store rate history; snapshot the active rate onto each session at creation time.
Timezone handling: Store all times in UTC; convert to local time only for display and labor-rule calculations.
Common Mistakes
- Using floats for money (accumulates rounding errors)
- Global payment watermark without per-session tracking (fails with late entries)
- Treating adjacent intervals as overlaps (end1 == start2 is valid)
- Not snapshotting rates (retroactive rate changes corrupt historical costs)
- Linear search for overlap detection (inefficient at scale)