← Questions

Most tasks finished before their deadlines

0
AmazonCodingLast asked Aug 2025

A coding interview question asked in Amazon's technical phone screen, last asked Aug 2025. It tests greedy, heap and scheduling.

You are given tasks, each with a positive duration and a deadline. One machine runs tasks one at a time, starting at time 0, in any order you choose; you may skip tasks. A task counts only if it finishes at or before its deadline. Return the largest number of tasks you can complete, and explain why your algorithm is correct.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • max_tasks(tasks: list[tuple[int, int]]) -> int — each task is (duration, deadline).

Example

max_tasks([(100, 200), (200, 1300), (1000, 1250), (2000, 3200)])  ->  3   # run 100, 1000, 200; skip 2000
max_tasks([(1, 2), (2, 4), (3, 6)])                               ->  3   # finish at 1, 3, 6
max_tasks([(3, 2), (4, 3)])                                       ->  0   # neither fits
max_tasks([(5, 5), (4, 6), (2, 6)])                               ->  2

Constraints

  • 0 <= len(tasks) <= 10^4; 1 <= duration <= 10^4; 1 <= deadline <= 10^9.
  • Target O(n log n).

Clarifying questions

  • Is a deadline inclusive (finishing exactly at the deadline counts)?
  • Can a task be paused and resumed later, or must it run to completion once started?
  • Do you want the count only, or the chosen tasks and their order?

What a strong answer covers

  • Sort by deadline; keep a running total of the chosen durations and a max-heap of them.
  • When the total passes the current deadline, drop the longest chosen task; the count never goes down and the total shrinks as much as possible.
  • An exchange argument for correctness: among all sets of the same size, the kept set has the smallest total time, and running it in deadline order is feasible.
  • O(n log n) time, O(n) space; tasks whose duration alone exceeds the deadline.

Follow-ups

  • Each task also has a value: maximize total value instead of count.
  • Return the schedule (the order and start times).
  • Several identical machines run in parallel.

Where it's asked

  • Amazon · Technical phone screen · Last asked Aug 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

greedy · heap · scheduling

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding