Select maximum tasks before deadlines
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Select maximum tasks before deadlines states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= tasks.length <= 10^4 (the list may also be empty, in which case the answer is 0)
- tasks[i].length == 2
- 1 <= duration <= 10^4
- 1 <= lastDay <= 10^9
- Time starts at 0; a chosen task with cumulative finish time t is valid only if t <= lastDay
Examples
Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
Expected Output: 3
Explanation: Take durations 100, 200, 1000 (skip 2000). Finishing in deadline order: 100 (<=200), 300 (<=1250 for the 1000-task? compute via greedy) — the greedy keeps 3 tasks; the 2000-duration task is evicted as the longest when the schedule overruns.
Input: [[1, 2], [2, 4], [3, 6]]
Expected Output: 3
Explanation: All three fit: cumulative finish times 1<=2, 3<=4, 6<=6.
Hints
- Process candidate tasks in non-decreasing order of deadline. Intuitively, to keep more tasks you should respect the earliest deadlines first.
- Keep a running sum of durations of the tasks you have committed to. When that sum exceeds the current task's deadline, you have over-committed and must drop exactly one task.
- Drop the task with the largest duration committed so far (a max-heap gives it in O(log n)). Removing the longest one frees the most time while keeping the count change neutral — you replace it with the shorter current task only if that helps.
- Correctness intuition: sorting by deadline means every task still in the heap fits under all later deadlines too; evicting the longest keeps the chosen set both feasible and maximal in count at each step (an exchange argument).