Implement a Timed Task Scheduler
Company: Tesla
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to implement timed task scheduling, encompassing time-based ordering, task execution semantics, concurrency control, and synchronization for runnable tasks.
Constraints
- 0 <= len(tasks) <= 200000
- 0 <= add_time, scheduled_time <= 10^9
- 1 <= duration <= 10^9
- Each task_id is an integer
- All computed times fit in a signed 64-bit integer
Examples
Input: [(0, 101, 5, 3), (2, 102, 4, 2), (6, 103, 6, 1)]
Expected Output: [(102, 4, 6), (101, 6, 9), (103, 9, 10)]
Explanation: Task 102 becomes ready at time 4 and runs first from 4 to 6. By time 6, tasks 101 and 103 are ready; 101 has the earlier scheduled_time, so it runs next, then 103.
Input: [(0, 1, 2, 5), (3, 2, 1, 2), (4, 3, 4, 1)]
Expected Output: [(1, 2, 7), (2, 7, 9), (3, 9, 10)]
Explanation: Task 1 starts at time 2 and blocks the scheduler until 7. Task 2 was added late but is already overdue when added, so it is ready from time 3 and has the smallest scheduled_time among ready tasks when the scheduler becomes free.
Input: [(0, 1, 5, 1), (1, 2, 5, 1), (0, 3, 5, 1)]
Expected Output: [(1, 5, 6), (3, 6, 7), (2, 7, 8)]
Explanation: All tasks are ready at time 5 with the same scheduled_time. Ties are broken by smaller add_time, then by original input order.
Input: [(5, 4, 8, 2), (0, 1, 3, 1), (2, 2, 10, 1), (1, 3, 3, 2)]
Expected Output: [(1, 3, 4), (3, 4, 6), (4, 8, 10), (2, 10, 11)]
Explanation: Tasks 1 and 3 are both ready at time 3, so they run first in tie-break order. The scheduler then waits until time 8 for task 4, and finally runs task 2 at time 10.
Input: []
Expected Output: []
Explanation: With no tasks, nothing is executed.
Hints
- A task becomes ready at time `max(add_time, scheduled_time)`.
- Sort tasks by ready time, then use a min-heap for the ready queue ordered by `(scheduled_time, add_time, original_index)`.