Shift Tracker and Earnings Simulator
Greedy & IntervalsAuto-graded · 16 test casesLast updated
Simulate employee shifts, structural updates, bonus intervals, filtering, and time-bounded payroll computations.
Design and implement a system to manage staff profiles, record work shifts, handle promotions, and evaluate payroll over arbitrary time windows.
You will process a sequence of operational commands. Each command returns a list of strings as its output.
System Rules & Logic
-
Staff Profiles:
- Every staff member has a unique string
name, a stringlevel, and an integerrate(earnings in cents per minute). - Staff profiles can be updated or promoted over time.
- Historical work shifts are always evaluated using the wage rate that was active when the shift started. Future changes to a staff member's wage rate do not modify the compensation of shifts logged prior to or during that rate change.
- Every staff member has a unique string
-
Shift Tracking:
- Shifts are logged using
ENTERandLEAVEcommands. - Time is represented in continuous non-negative integer minutes.
- All shifts are strictly non-overlapping per worker and have positive durations.
- Rate updates, additions, and promotions only occur when the worker is not currently clocked in.
- Shifts are logged using
-
Bonus Hours:
- Bonus multipliers cover half-open time intervals
[start, end). - During a bonus interval, any worked minute yields double the base pay (i.e., base rate + 1x bonus rate = 2x base rate).
- Multiple bonus intervals can overlap. However, overlapping bonus intervals do not stack beyond double pay—a minute covered by one or more bonus intervals is always paid at exactly twice the normal rate.
- Bonus multipliers cover half-open time intervals
-
Payroll Calculation (
TOTAL):- For a given window
[start, end), calculate the total earnings across all completed shifts for all workers. - Only the portion of any shift that overlaps with the query interval
[start, end)is compensated. - Earnings for a clipped shift segment of duration $D$ worked at rate $R$ with $B$ bonus minutes within that segment is equal to $R \times (D + B)$.
- For a given window
Operations & Output Formats
["ADD", name, level, rate]: Register a new worker. Returns["OK"].["GET", name]: Retrieve worker details. Returns[name, level, rate].["UPDATE", name, level, rate]and["PROMOTE", name, level, rate]: Update worker attributes. Returns["OK"].["ENTER", name, time]: Clock in worker attime. Returns["OK"].["LEAVE", name, time]: Clock out worker attime. Returns["OK"].["FILTER", field, value, sortField]: Find all workers wherefield("name","level", or"rate") equalsvalue. Return a list of matching worker names sorted bysortField("name","level", or"rate"). Ties insortFieldmust be broken by workernamein ascending lexicographical order. String comparison is used for"name"and"level", while numeric comparison is used for"rate". If no workers match, return an empty array[].["BONUS", start, end]: Add a double-pay time interval[start, end). Returns["OK"].["TOTAL", start, end]: Compute total earnings for all workers in time range[start, end). Returns[totalCents], formatted as a decimal string with no leading zeros.
Constraints
- Total operations $\le 2000$. Number of distinct workers $\le 200$.
- Time ranges are non-negative integers up to $1{,}000{,}000$. Rates are non-negative integers up to $1{,}000{,}000$.
- All inputs are well-formed and valid according to the operational rules.
Examples
Example 1
Input: worker_payroll([['ADD', 'Ada', 'L1', '10'], ['ENTER', 'Ada', '0'], ['LEAVE', 'Ada', '10'], ['BONUS', '3', '5'], ['TOTAL', '0', '10'], ['PROMOTE', 'Ada', 'L2', '20'], ['GET', 'Ada']])
Output: [['OK'], ['OK'], ['OK'], ['OK'], ['120'], ['OK'], ['Ada', 'L2', '20']]
Example 2
Input: worker_payroll([['ADD', 'A', 'L1', '5'], ['ADD', 'B', 'L2', '7'], ['FILTER', 'level', 'L1', 'name'], ['FILTER', 'rate', '7', 'rate'], ['GET', 'B']])
Output: [['OK'], ['OK'], ['A'], ['B'], ['B', 'L2', '7']]
Hints
Hint 1
Capture the worker's current pay rate at the exact moment of 'ENTER' so that subsequent rate changes do not corrupt past shift rates.
Hint 2
Bonus periods can overlap or be added out of order. Merge all recorded bonus intervals into disjoint blocks before processing a 'TOTAL' query.
Hint 3
For each completed shift, compute its intersection with the total query range [query_start, query_end). If they intersect, compute the intersection of that clipped shift with each merged bonus block to find total bonus minutes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks us to simulate a stateful operational tracking system supporting profile management, filtering, active session tracking, bonus intervals, and windowed payroll calculations.
Key points to address:
- Historical Wage Rates: A shift must retain the pay rate active at the moment
ENTERwas executed. When handlingENTER, we capture(start_time, current_rate). UponLEAVE, we write(start_time, end_time, rate)into the worker's shift history. SubsequentUPDATEorPROMOTEcalls modify only the worker's active rate without affecting completed sessions. - Non-Stacking Bonus Intervals: Multiple bonus intervals can overlap or be registered out of order. To prevent double-counting bonus pay beyond 2x, we merge overlapping bonus intervals into a sorted list of disjoint intervals prior to evaluating a
TOTALquery. - Clipped Calculations: For each shift
[s_start, s_end)with rate $R$:- Clip the shift to the query range
[q_start, q_end)to obtain[c_start, c_end). - Calculate duration $D = c_end - c_start$.
- Calculate overlap $B$ between
[c_start, c_end)and each merged bonus interval. - Add $R \times (D + B)$ to the running payroll sum.
- Clip the shift to the query range
Complexity Analysis
- Time Complexity:
ADD,GET,UPDATE,PROMOTE,ENTER,LEAVE,BONUS: $O(1)$ amortized operations.FILTER: $O(W \log W)$, where $W$ is the number of active workers ($W \le 200$).TOTAL: Merging $B$ bonus intervals takes $O(B \log B)$. Calculating compensation over $S$ sessions takes $O(S \cdot B')$, where $B'$ is the number of merged bonus blocks. Given $N \le 2000$ operations total, this approach operates well within time bounds.
- Space Complexity:
- $O(W + S + B)$ space to store worker profiles, recorded shifts, and bonus intervals.
Python Reference Solution
from typing import List
def worker_payroll(operations: List[List[str]]) -> List[List[str]]:
workers = {}
bonus_intervals = []
result = []
def get_merged_bonuses():
if not bonus_intervals:
return []
sorted_intervals = sorted(bonus_intervals)
merged = [list(sorted_intervals[0])]
for start, end in sorted_intervals[1:]:
if start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
for op in operations:
cmd = op[0]
if cmd == "ADD":
name, level, rate = op[1], op[2], int(op[3])
workers[name] = {"level": level, "rate": rate, "active": None, "sessions": []}
result.append(["OK"])
elif cmd == "GET":
name = op[1]
w = workers[name]
result.append([name, w["level"], str(w["rate"])])
elif cmd in ("UPDATE", "PROMOTE"):
name, level, rate = op[1], op[2], int(op[3])
workers[name]["level"] = level
workers[name]["rate"] = rate
result.append(["OK"])
elif cmd == "ENTER":
name, time = op[1], int(op[2])
w = workers[name]
w["active"] = (time, w["rate"])
result.append(["OK"])
elif cmd == "LEAVE":
name, time = op[1], int(op[2])
w = workers[name]
start_time, rate = w["active"]
w["sessions"].append((start_time, time, rate))
w["active"] = None
result.append(["OK"])
elif cmd == "FILTER":
field, val, sort_field = op[1], op[2], op[3]
matched = []
for name, w in workers.items():
if field == "name":
is_match = (name == val)
elif field == "level":
is_match = (w["level"] == val)
else:
is_match = (w["rate"] == int(val))
if is_match:
matched.append((name, w))
if sort_field == "name":
matched.sort(key=lambda x: x[0])
elif sort_field == "level":
matched.sort(key=lambda x: (x[1]["level"], x[0]))
else:
matched.sort(key=lambda x: (x[1]["rate"], x[0]))
result.append([x[0] for x in matched])
elif cmd == "BONUS":
bonus_intervals.append((int(op[1]), int(op[2])))
result.append(["OK"])
elif cmd == "TOTAL":
q_start, q_end = int(op[1]), int(op[2])
merged_b = get_merged_bonuses()
total_pay = 0
for w in workers.values():
for s_start, s_end, rate in w["sessions"]:
clip_start = max(s_start, q_start)
clip_end = min(s_end, q_end)
if clip_start >= clip_end:
continue
duration = clip_end - clip_start
bonus_mins = 0
for b_start, b_end in merged_b:
if b_end <= clip_start:
continue
if b_start >= clip_end:
break
overlap = max(0, min(clip_end, b_end) - max(clip_start, b_start))
bonus_mins += overlap
total_pay += rate * (duration + bonus_mins)
result.append([str(total_pay)])
return result