Task Dependency Resolver - Problem

Given a list of tasks and their dependencies, find a valid execution order that respects all dependencies. If there are circular dependencies, return "CYCLE".

Each task is represented by an integer, and dependencies are given as pairs [a, b] meaning task b depends on task a (so a must be completed before b).

Requirements:

  • Return any valid topological ordering of tasks
  • If a cycle exists, return the string "CYCLE"
  • Tasks are numbered from 0 to n-1

Input & Output

Example 1 — Basic Dependency Chain
$ Input: numTasks = 3, dependencies = [[0,1],[1,2]]
Output: [0,1,2]
💡 Note: Task 1 depends on task 0, and task 2 depends on task 1. So the valid order is 0 → 1 → 2.
Example 2 — No Dependencies
$ Input: numTasks = 2, dependencies = []
Output: [0,1]
💡 Note: No dependencies between tasks, so any order is valid. [0,1] or [1,0] both work.
Example 3 — Circular Dependency
$ Input: numTasks = 2, dependencies = [[0,1],[1,0]]
Output: CYCLE
💡 Note: Task 0 depends on task 1, and task 1 depends on task 0. This creates a circular dependency.

Constraints

  • 0 ≤ numTasks ≤ 104
  • 0 ≤ dependencies.length ≤ 5000
  • dependencies[i].length == 2
  • 0 ≤ ai, bi < numTasks
  • ai ≠ bi

Visualization

Tap to expand
INPUTALGORITHMRESULTTasks: 0, 1, 2Dependencies: [0,1], [1,2]0121Count In-degreesTask 0: 0 incomingTask 1: 1 incomingTask 2: 1 incoming2Process Zero In-degreeQueue: [0]Process 0, add 1 to queue3Continue BFSQueue: [1,2]Process all tasks[0, 1, 2]Valid Execution Order✓ Task 0 first (no dependencies)✓ Task 1 after 0✓ Task 2 after 1No Cycles DetectedKey Insight:Use Kahn's algorithm to process tasks with zero dependencies first,removing edges as you go - if any tasks remain unprocessed, there's a cycle.TutorialsPoint - Task Dependency Resolver | Kahn's Algorithm (BFS)
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
125.0K Views
High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen