KatInterview

Lexicographic Topological Sort of a Task Graph

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphsheaps

Last updated

Tests directed graph construction, cycle detection via Kahn's algorithm, and deterministic tie-breaking with a min-heap to produce the lexicographically smallest valid ordering.

Pipeline Task Scheduler

You are building a scheduler for a data pipeline. Each pipeline consists of named tasks, and some tasks must complete before others can begin. Your job is to produce a valid execution order for all tasks.

You are given:

  • tasks: a list of unique task name strings.
  • prereqs: a list of pairs [a, b], where each pair means task a must finish before task b starts.

Return a list of all task names in a valid execution order — that is, for every pair [a, b] in prereqs, task a must appear somewhere before task b in the output.

Rules

  1. If the dependency graph contains a cycle (making it impossible to schedule all tasks), return an empty list [].
  2. When more than one task is eligible to run at the same point, always pick the one that comes first alphabetically. Apply this rule at every step so the result is the lexicographically smallest valid order overall.
  3. Every task in tasks must appear in the output exactly once, unless a cycle is detected.

Constraints

  • 1 <= len(tasks) <= 1000
  • 0 <= len(prereqs) <= 5000
  • Task names contain only lowercase English letters and underscores, and are between 1 and 30 characters long.
  • Every name that appears in prereqs is guaranteed to also appear in tasks.
  • prereqs may contain duplicate pairs; treat them as a single dependency.

Examples

Example 1

Input: schedule_tasks(['auth', 'risk_engine', 'order_routing', 'market_data'], [['auth', 'risk_engine'], ['auth', 'order_routing'], ['market_data', 'order_routing'], ['risk_engine', 'order_routing']])

Output: ['auth', 'market_data', 'risk_engine', 'order_routing']

Example 2

Input: schedule_tasks(['service_a', 'service_b'], [['service_a', 'service_b'], ['service_b', 'service_a']])

Output: []

Hints

Hint 1

Model the tasks as nodes in a directed graph where an edge from a to b means a must come before b. What property does a node have when all its predecessors have already been scheduled?

Hint 2

Kahn's algorithm processes nodes with in-degree zero. To enforce alphabetical tie-breaking at every step, think about which data structure always gives you the minimum element efficiently.

Hint 3

Duplicate edges in prereqs would inflate in-degree counts, causing nodes to wait for prerequisites that were already satisfied. Store neighbors in a set and only increment in-degree the first time you see each edge.