Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: n ≤ 10⁵ tasks with durations and deadlines; complete as many tasks as possible, one at a time, each finishing by its deadline. Which greedy works?

  1. A. Sort by duration and take while time allows
  2. B. Sort by deadline and skip any task that does not fit
  3. C. Sort by deadline; add each task to a max-heap of durations, and if total time exceeds the deadline, drop the longest task taken so far – O(n log n)
  4. D. Take tasks in input order

Correct answer: C. Sort by deadline; add each task to a max-heap of durations, and if total time exceeds the deadline, drop the longest task taken so far – O(n log n)

Processing by deadline keeps feasibility checks simple; when the schedule overflows, removing the longest task frees the most time while losing only one task – an exchange argument shows this is optimal. Simply skipping the current task can be worse than removing an earlier long one; sorting by duration ignores deadlines.

More Coding Interview Problems questions

Exams that ask this topic