Freelance Crew Pay Tracker With Rolling Settlements
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests the ability to design an in-memory ledger class driven by an operation list, maintaining running cost totals and an idempotent pay-cutoff pointer.
Freelance Crew Pay Tracker With Rolling Settlements
You are building a payroll tool for a production company that hires freelance crew members on short-term work blocks. Each crew member earns a fixed hourly rate, and the company needs to track what has been earned, what has already been paid out, and what is still owed — all in memory.
Implement a function that accepts a sequence of named operations and their arguments, executes them in order against a single in-memory tracker, and returns a result list of the same length. Operations that produce no meaningful value append None to the result list.
Operations
add_worker — [worker_id, hourly_rate_usd]
Registers a crew member with the given string ID and their USD hourly rate (a number). Appends None.
log_call — [worker_id, start_time, end_time]
Records one completed work block for the given worker. start_time and end_time are integer timestamps in seconds. The cost of the block is hourly_rate * (end_time - start_time) / 3600. Appends None.
total_cost — []
Returns the total labor cost accrued across all workers and all logged work blocks, regardless of whether any of it has been paid. Appends that number.
pay_through — [cutoff_time]
Marks all work performed up to cutoff_time as settled. Calling this again with the same or any earlier timestamp must be a no-op — no amount already paid out can be counted as unpaid again. Appends None.
unpaid_balance — []
Returns the total wages still owed after all settlements applied so far. Appends that number.
How unpaid work is calculated after a settlement
After pay_through(cutoff) is called, the unpaid portion of a logged block [start, end) is the cost of the interval [max(start, cutoff), end). Any seconds at or before the cutoff are considered paid.
If a work block is logged after a pay_through call and its start time falls before the current cutoff, only the portion from the cutoff onward is treated as unpaid (the pre-cutoff portion still counts toward total_cost).
Constraints
- All timestamps are non-negative integers (seconds).
end_time >= start_timefor everylog_call.hourly_rate_usdis a positive number (float or int).worker_idis a non-empty string; a worker is registered before any of their calls are logged.- There is at most one global settlement pointer shared across all workers (not per-worker).
pay_throughis never called with a time earlier than the first such call; if it is, treat it as a no-op.total_costandunpaid_balancemay be called any number of times and always reflect the current state.- 1 ≤ total number of operations ≤ 10,000.
- 0 ≤ timestamps ≤ 10^9.
- 0 < hourly_rate_usd ≤ 10,000.
Examples
Example 1
Input: crew_pay_tracker(['add_worker', 'log_call', 'total_cost', 'pay_through', 'unpaid_balance', 'pay_through', 'unpaid_balance'], [['crew_7', 42], ['crew_7', 0, 7200], [], [3600], [], [3600], []])
Output: [None, None, 84, None, 42, None, 42]
Hints
Hint 1
Keep two running numeric totals — one for all accrued cost and one for unpaid cost — so that `total_cost` and `unpaid_balance` are O(1) lookups rather than re-scanning every logged block each time they are called.
Hint 2
When `pay_through(cutoff)` is called with a strictly later cutoff than before, you need to recompute the unpaid balance. Walk every logged block and for each one count only the seconds that fall after the new cutoff: `max(0, end - max(start, cutoff))`.
Hint 3
When a new work block is logged, the unpaid portion starts not at `start_time` but at `max(start_time, current_cutoff)` — the pre-cutoff seconds belong to total cost but not to unpaid balance.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that total_cost and unpaid_balance can be called far more often than any other operation, so they should be O(1). We achieve this by maintaining two running numeric totals that are updated incrementally as work blocks are logged and as the settlement pointer advances.
State
rates— maps each worker ID to their hourly rate.blocks— append-only list of every logged(worker_id, start, end)tuple.cutoff— a single global timestamp representing "everything before this point has been paid." Starts asNone(nothing settled yet) and only ever moves forward.total— sum of the cost of every block ever logged, regardless of payment status.unpaid— sum of the cost of the unsettled portion of every block.
Logging a work block
The full cost of the block is added to total. For unpaid, we only count the seconds that fall after the current cutoff: the unpaid start is max(block_start, cutoff) (or just block_start if nothing has been settled yet). This handles the case where a block is logged retroactively with a start time that has already been paid through.
Settling wages (pay_through)
If the requested cutoff is the same as or earlier than the current one, it is a no-op — the pointer never moves backward.
When the cutoff does advance, the simplest correct approach is to recompute unpaid from scratch by walking every logged block and counting only the seconds after the new cutoff: max(0, end - max(start, cutoff)). This is O(n) in the number of logged blocks, which is acceptable here. For systems with very large call histories and frequent settlements, you could index blocks by worker and by start time to skip already-fully-settled blocks faster — a useful follow-up to discuss.
Why this is correct
totalis append-only and never decremented, so it is always accurate regardless of settlements.- The cutoff pointer only ever moves forward, which guarantees that already-settled seconds can never re-enter
unpaid. - Blocks logged after a settlement that overlap the cutoff are split at the pointer, so no pre-cutoff seconds are double-counted as unpaid.
Complexity
| Operation | Time | Space |
|---|---|---|
add_worker | O(1) | O(1) |
log_call | O(1) | O(1) amortized |
total_cost | O(1) | — |
unpaid_balance | O(1) | — |
pay_through | O(n) calls logged | — |
Overall space is O(w + n) where w is the number of workers and n is the number of logged blocks.
from typing import List
def crew_pay_tracker(operations: List[str], arguments: List[List]) -> List:
rates = {} # worker_id -> hourly rate (USD)
blocks = [] # (worker_id, start_time, end_time)
cutoff = None # global settlement pointer (seconds)
total = 0.0
unpaid = 0.0
results = []
for operation, args in zip(operations, arguments):
if operation == "add_worker":
worker_id, hourly_rate_usd = args
rates[worker_id] = hourly_rate_usd
results.append(None)
elif operation == "log_call":
worker_id, start_time, end_time = args
rate = rates[worker_id]
duration = end_time - start_time
# Full block always goes into total cost
total += rate * duration / 3600
blocks.append((worker_id, start_time, end_time))
# Only the portion after the current cutoff is unpaid
unpaid_start = start_time if cutoff is None else max(start_time, cutoff)
unpaid += rate * max(0, end_time - unpaid_start) / 3600
results.append(None)
elif operation == "total_cost":
results.append(total)
elif operation == "pay_through":
new_cutoff = args[0]
# Advance the pointer only if the new cutoff is strictly later
if cutoff is None or new_cutoff > cutoff:
cutoff = new_cutoff
# Recompute unpaid balance from scratch using the new cutoff
unpaid = sum(
rates[wid] * max(0, end - max(start, cutoff)) / 3600
for wid, start, end in blocks
)
results.append(None)
elif operation == "unpaid_balance":
results.append(unpaid)
else:
raise ValueError(f"unknown operation: {operation}")
return results