KatInterview

Schedule Tasks by Deadline and Priority

Heaps, Sorting & SearchAuto-graded · 15 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingcustom sort keysheaps

Last updated

Tests the ability to sort a list of tasks using a multi-key custom comparator involving deadlines, priorities, and tie-breaking rules.

Schedule Tasks by Deadline and Priority

You are building a task scheduler. Each task is represented as a dictionary with the following fields:

FieldTypeDescription
"id"strUnique task identifier
"deadline"intThe time unit by which the task must be completed (lower = sooner)
"priority"intUrgency level (higher = more urgent)
"duration"intHow many time units the task takes to run

Given a list of such task dictionaries, return a list of task id strings ordered by the following scheduling rules, applied in order:

  1. Earliest deadline first — tasks with a smaller deadline come first.
  2. Highest priority first — among tasks with equal deadlines, tasks with a larger priority come first.
  3. Shortest duration first — among tasks with equal deadline and priority, tasks with a smaller duration come first.
  4. Lexicographically smallest id first — among tasks identical on all above fields, sort by id in ascending lexicographic order.

Return only the list of id strings in the computed order.

Constraints

  • 0 <= len(tasks) <= 2000
  • Each deadline is an integer with 1 <= deadline <= 10^6
  • Each priority is an integer with 1 <= priority <= 10^9
  • Each duration is an integer with 1 <= duration <= 10^4
  • Each id is a non-empty string of lowercase letters and digits; all id values are unique.
  • The result must be deterministic: all four tie-breaking rules ensure exactly one valid ordering.

Examples

Example 1

Input: schedule_tasks([{'id': 'alpha', 'deadline': 5, 'priority': 3, 'duration': 2}, {'id': 'beta', 'deadline': 3, 'priority': 5, 'duration': 4}, {'id': 'gamma', 'deadline': 5, 'priority': 3, 'duration': 1}])

Output: ['beta', 'gamma', 'alpha']

Example 2

Input: schedule_tasks([{'id': 'x1', 'deadline': 10, 'priority': 7, 'duration': 3}, {'id': 'x2', 'deadline': 10, 'priority': 7, 'duration': 3}, {'id': 'x3', 'deadline': 10, 'priority': 7, 'duration': 3}])

Output: ['x1', 'x2', 'x3']

Example 3

Input: schedule_tasks([])

Output: []

Hints

Hint 1

Think about what tuple to return from a key function so that Python's built-in sort handles all four criteria at once.

Hint 2

Remember that Python sorts tuples lexicographically — so the order of elements in your key tuple directly controls which criterion is applied first.

Hint 3

For 'highest priority first', you need to reverse that one dimension. Negating an integer value lets you flip a single field's sort direction without affecting the others.