Implement a Worker Hours Register
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Implement an in-memory `WorkHoursRegister` system for contract workers. The system tracks office entry and exit events, completed work time, promotions, salary over time ranges, and special grant periods that double pay.
Support the following operations:
1. Basic worker tracking
- `add_worker(id, position, hourly_rate)`: Add a worker with the given position and hourly compensation. Return `false` if `id` already exists; otherwise return `true`.
- `register(id, timestamp)`: Toggle the worker's office status. If the worker is outside the office, this starts a new work session at `timestamp`. If the worker is already inside, this ends the current session at `timestamp`.
- `get(id)`: Return the worker's total completed work time. If the worker is currently inside the office, the ongoing session does not count yet.
2. Ranking
- `top_n_workers(n, position)`: Return the top `n` workers for the given position, formatted as strings like `"worker_id(total_time)"`.
- Sort by completed work time in descending order. If two workers have the same time, sort by `id` in lexicographic ascending order.
3. Promotions and salary
- `promote(id, new_position, new_hourly_rate)`: Register a promotion request with delayed effect.
- If the promotion is requested while the worker is in the office, the current session continues under the old position and old hourly rate. The new position and hourly rate take effect only the next time the worker enters the office.
- `calc_salary(id, start, end)`: Compute the worker's pay earned within the time window `[start, end]` by summing, for each completed work session, the duration of overlap with the query window multiplied by the hourly rate that was active during that session.
4. Grant periods
- `register_grant(start, end)`: Register a time interval during which qualifying sessions receive double pay.
- Upgraded `calc_salary`: If a completed work session is fully contained within any registered grant interval, that entire session is paid at double rate. Partial overlap with a grant interval does not qualify.
- `get_grant_bonus(start, end)`: The pair `(start, end)` must exactly match a previously registered grant interval. Return the total extra bonus paid across all workers for that grant interval, where the bonus is the additional one extra multiple of pay for qualifying sessions.
Design suitable data structures and implement all operations efficiently.
Quick Answer: This question evaluates data structures and algorithms skills for temporal event tracking, interval arithmetic, stateful session management, ranking, and aggregate payroll computations including grant-based bonuses.