Shift Ledger: Rates, Promotions and Bonus Windows
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a command stream for a shift ledger with deferred pay-rate changes, merged global bonus windows and a ranking of employees by hours worked.
Shift Ledger
You are building a small in-memory ledger that records employee shifts and computes pay. Instead of a class, you implement one function that replays a list of commands in order and returns one result per command.
commands[i] is the name of a command and params[i] is the list of its arguments. The function returns a list results of the same length, where results[i] is the output of command i.
Commands
| Command | Arguments | Output |
|---|---|---|
register_employee | emp_id, base_rate | None |
schedule_promotion | emp_id, effective_time, new_rate | None |
add_bonus_window | start_time, end_time | None |
clock_in | emp_id, timestamp | None |
clock_out | emp_id, timestamp | None |
get_total_pay | emp_id | total pay as a number |
get_top_k_worked | k | list of employee ids |
Rules
Registration. register_employee creates an employee whose current hourly rate is base_rate, with no hours and no pay. Registering an id that already exists replaces that employee with a fresh record.
Promotions. schedule_promotion queues a rate change for one employee. A queued promotion becomes active only at one of that employee's clock-ins, never in the middle of a shift.
- At
clock_in(emp_id, timestamp), every queued promotion of that employee witheffective_time <= timestampis applied and removed from the queue. - Due promotions are applied in ascending
effective_time. Promotions with equaleffective_timeare applied in the order they were scheduled. The last one applied becomes the employee's current rate. - Promotions with
effective_time > timestampstay queued. - The current rate at the end of this step is locked in for the whole shift. Promotions scheduled while the shift is open do not change that shift's rate.
Bonus windows. add_bonus_window(start_time, end_time) adds a global half-open window [start_time, end_time). Windows are shared by all employees. Overlapping or touching windows behave as one merged window, so no time unit is ever rewarded more than once.
Shifts and pay. clock_in opens a shift at timestamp. clock_out closes it, so the shift covers [clock_in_time, timestamp). At the moment of clock_out, take the bonus windows that exist at that moment and compute:
duration = timestamp - clock_in_timebonus_hours= number of time units of the shift that lie inside the union of bonus windowsnormal_hours = duration - bonus_hours- shift pay =
locked_rate * (normal_hours + 2.0 * bonus_hours)
The duration is added to the employee's total worked time and the shift pay is added to their total pay. A bonus window added after a shift has closed never changes that shift's pay.
Queries.
get_total_payreturns the sum of the pay of the employee's closed shifts, or0.0if none are closed. Open shifts contribute nothing.get_top_k_workedreturns the ids of thekemployees with the largest total closed-shift duration, in descending order of duration. Ties are broken byemp_idin ascending lexicographic order. Ifkexceeds the number of employees, return all of them. Employees with zero hours are included and ranked by the same rule.
All timestamps and durations are integers (hours). Every employee id used in a command was registered earlier.
Constraints
0 <= timestamp <= 10^9, and all window and promotion times are integers in the same range.0 <= start_time < end_time <= 10^9for every bonus window.- For any single employee,
clock_inandclock_outalternate, and a shift always has a strictly positive length (clock_outtimestamp is greater than the matchingclock_intimestamp). A new shift starts after the previous one ends. commandsandparamshave the same length, at most10^5.- Rates are non-negative numbers.
Examples
Example 1
Input: run_shift_ledger(['register_employee', 'add_bonus_window', 'add_bonus_window', 'clock_in', 'clock_out', 'schedule_promotion', 'clock_in', 'clock_out', 'get_total_pay', 'get_top_k_worked'], [['E1', 20], [2, 5], [4, 7], ['E1', 1], ['E1', 4], ['E1', 5, 30], ['E1', 6], ['E1', 9], ['E1'], [1]])
Output: [None, None, None, None, None, None, None, None, 220, ['E1']]
Example 2
Input: run_shift_ledger(['register_employee', 'register_employee', 'add_bonus_window', 'clock_in', 'clock_in', 'clock_out', 'clock_out', 'get_total_pay', 'get_total_pay', 'get_top_k_worked'], [['A', 10], ['B', 15], [0, 3], ['A', 0], ['B', 1], ['A', 3], ['B', 5], ['A'], ['B'], [2]])
Output: [None, None, None, None, None, None, None, 60, 90, ['B', 'A']]
Hints
Hint 1
Per employee, keep the current rate, the open shift's start time and locked rate, total hours and total pay. Keep a separate list of scheduled promotions.
Hint 2
At clock-in, sort the employee's promotions by effective time (a stable sort keeps scheduling order for ties), apply every due one, and keep the rest. Store the resulting rate with the open shift.
Hint 3
Keep the bonus windows as a sorted list of disjoint intervals and merge a new window with every interval it overlaps or touches. At clock-out, sum the intersection of the shift with each merged window.
Hint 4
Rank employees with the sort key (-total_hours, emp_id) and slice the first k.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a simulation. Each rule maps to a small piece of state, and the main work is getting the timing of each rule right.
Per-employee record. Store the current rate, the pending promotions, the open shift (start time plus locked rate), total hours and total pay.
Promotions. Pending promotions are kept sorted by effective time. A stable sort preserves scheduling order for ties. At clock_in(t), walk through them, apply every one with effective_time <= t so the last applied one wins, and keep the others. The resulting rate is stored together with the shift start. Later promotions therefore cannot affect a shift that is already open.
Bonus windows. Keep a sorted list of disjoint, non-touching intervals. To insert [s, e), copy the intervals that end strictly before s, absorb every interval that overlaps or touches the new one by widening s and e, then place the merged interval and copy the remaining intervals that start strictly after e. Merging means each time unit is counted once.
Closing a shift. At clock_out, compute the overlap of [start, end) with each merged window. Bonus hours pay double and the rest pay normally, so the pay is rate * (normal + 2 * bonus). Pay is computed only at clock-out, so only the windows known at that moment count.
Top-k. Sort employees by (-hours, emp_id) and take the first k. This gives descending hours with ties broken alphabetically, and zero-hour employees are included naturally.
Why it is correct
- The merged window list is always disjoint, so summing per-window intersections measures the union exactly, with no double counting.
- Applying promotions only inside
clock_inand storing the rate with the open shift implements "first clock-in at or after the effective time" and "mid-shift promotions do not apply". - Computing pay at clock-out matches the rule that later windows never alter closed shifts.
- Checking sample 1: windows merge to
[2, 7). Shift[1, 4)at 20 has 2 bonus hours, so pay is20 * (1 + 4) = 100. The promotion at time 5 applies at clock-in 6, so shift[6, 9)at 30 has 1 bonus hour, so pay is30 * (2 + 2) = 120. The total is 220.
Complexity
Let W be the number of merged windows, E the number of employees and P the number of pending promotions for an employee.
add_bonus_window: O(W)clock_out: O(W)schedule_promotion: O(P log P)clock_in: O(P)get_total_pay: O(1)get_top_k_worked: O(E log E)- Space: O(E + W + total promotions)
This is simple and fast enough for the stated limits. Binary search over a prefix-sum array of window lengths, a heap for promotions, and heapq.nsmallest for the ranking would give logarithmic updates if needed.
Reference solution
from typing import List
def run_shift_ledger(commands: List[str], params: List[List]) -> List:
staff = {}
windows = [] # sorted, disjoint, non-touching (start, end) pairs
def add_window(start, end):
nonlocal windows
merged = []
placed = False
for left, right in windows:
if right < start:
merged.append((left, right))
elif end < left:
if not placed:
merged.append((start, end))
placed = True
merged.append((left, right))
else:
start = min(start, left)
end = max(end, right)
if not placed:
merged.append((start, end))
windows = merged
def bonus_overlap(start, end):
total = 0
for left, right in windows:
if right <= start:
continue
if left >= end:
break
total += max(0, min(end, right) - max(start, left))
return total
def finish_shift(rec, end_time):
start_time, rate = rec["open"]
duration = end_time - start_time
bonus = bonus_overlap(start_time, end_time)
normal = duration - bonus
rec["hours"] += duration
rec["pay"] += rate * (normal + 2.0 * bonus)
rec["open"] = None
out = []
for cmd, args in zip(commands, params):
if cmd == "register_employee":
emp_id, rate = args
staff[emp_id] = {
"rate": rate,
"promos": [],
"open": None,
"hours": 0,
"pay": 0.0,
}
out.append(None)
elif cmd == "schedule_promotion":
emp_id, eff, new_rate = args
rec = staff[emp_id]
rec["promos"].append((eff, new_rate))
rec["promos"].sort(key=lambda p: p[0])
out.append(None)
elif cmd == "add_bonus_window":
add_window(*args)
out.append(None)
elif cmd == "clock_in":
emp_id, ts = args
rec = staff[emp_id]
pending = []
for eff, new_rate in rec["promos"]:
if eff <= ts:
rec["rate"] = new_rate
else:
pending.append((eff, new_rate))
rec["promos"] = pending
rec["open"] = (ts, rec["rate"])
out.append(None)
elif cmd == "clock_out":
emp_id, ts = args
finish_shift(staff[emp_id], ts)
out.append(None)
elif cmd == "get_total_pay":
out.append(staff[args[0]]["pay"])
elif cmd == "get_top_k_worked":
k = args[0]
ranked = sorted(staff.items(), key=lambda kv: (-kv[1]["hours"], kv[0]))
out.append([emp_id for emp_id, _ in ranked[:k]])
else:
raise ValueError(f"unknown command: {cmd}")
return out