Implement DelayQueue with Idempotent Task Execution
Company: Pinterest
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates implementation skills in time-based task scheduling, idempotent execution semantics, and concurrency control, emphasizing data-structure selection and synchronization trade-offs.
Constraints
- 1 <= len(operations) <= 200000
- run_at and now are integers in the range [0, 10^12]
- id and task are non-empty strings of length <= 64
- Within a single poll, tasks execute in ascending run_at; ties broken by schedule order
- Each ID executes at most once across all polls; subsequent tasks with the same ID are skipped when popped
- Use O(n) additional space; aim for O(log n) schedule and pop operations
Hints
- Maintain a min-heap keyed by (run_at, sequence_number) to fetch the next due task and break ties by insertion order.
- Use a hash set to record executed IDs; skip any popped task whose ID is already in the set.
- On poll(now), pop while heap top run_at <= now; for each popped task, atomically check-and-add the ID to the executed set before executing.
- Return tasks executed in the order they are processed during the poll.