KatInterview

Alphabetical Job Scheduler with Prerequisite Rules

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstopological-sortheapgraph

Last updated

Produce a full run order for jobs under prerequisite constraints, always picking the alphabetically smallest available job, or return an empty list if a cycle exists.

Alphabetical Job Scheduler

A scheduler needs to run a collection of jobs. Each job has a unique name, and some jobs may only start after others have finished.

You are given:

  • jobs: a list of distinct job names.
  • requirements: a list of pairs [before, after]. Each pair means the job before must run earlier than the job after.

Build a single run order that contains every job and satisfies these rules:

  1. Each job appears in the order exactly once.
  2. For every pair [before, after], before appears at an earlier position than after.
  3. At each step, consider all jobs whose prerequisites have already been scheduled. Among those, choose the one whose name is smallest in standard lexicographic (dictionary) order.
  4. Jobs that are not mentioned in any pair are still scheduled, following the same selection rule as everything else.

If the requirements contain a cycle, so that no order can satisfy rule 2 for all jobs, return an empty list []. Do not return a partial order. A cycle in any part of the graph makes the whole result empty.

Constraints

  • 1 <= len(jobs) <= 20,000
  • 0 <= len(requirements) <= 50,000
  • Each job name has between 1 and 20 lowercase English letters.
  • All names in jobs are distinct.
  • In each pair [a, b], both a and b appear in jobs, and a != b.
  • The same pair may appear more than once in requirements.
  • The order of names in jobs carries no meaning for the result.

Examples

Example 1

Input: schedule_jobs(['build', 'test', 'lint', 'deploy'], [['lint', 'test'], ['build', 'test'], ['test', 'deploy']])

Output: ['build', 'lint', 'test', 'deploy']

Example 2

Input: schedule_jobs(['zeta', 'alpha', 'beta'], [])

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

Hints

Hint 1

Count, for each job, how many prerequisite pairs point at it. Jobs with a count of zero are the ones that can run right now.

Hint 2

You need to repeatedly extract the smallest name from the set of currently runnable jobs. Which data structure supports that efficiently while new jobs keep becoming runnable?

Hint 3

After scheduling a job, lower the count of each job that depends on it. Duplicate pairs raise the count multiple times and lower it multiple times, so they stay consistent. If you end up with fewer scheduled jobs than total jobs, a cycle blocked some of them.