Quick Overview

A practical coding problem about scheduling dependent tasks: given task names and prerequisite pairs, return a run order in which every task follows its prerequisites, breaking ties by name, or an empty list when a cycle makes scheduling impossible. It tests dependency graph processing and cycle detection.

Schedule Dependent Tasks So Each Runs After Its Prerequisites

Company: Apple

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

A job scheduler receives a list of task names and a list of dependencies between them. A dependency `[before, after]` means task `before` must finish before task `after` can start. Tasks run one at a time. Return the order in which to run all the tasks so that every task starts only after all of its prerequisites have finished. When several tasks are ready at the same time, run the one with the smallest name. If the dependencies contain a cycle, so that some tasks can never start, return an empty list. ### Function Signature ```python def schedule_tasks(tasks: list[str], dependencies: list[list[str]]) -> list[str]: ``` ### Rules - A task is ready when every task it depends on has already been placed in the order. A task with no prerequisites is ready from the start. - Whenever more than one task is ready, the next task is the smallest ready name under Python string comparison. - When scheduling succeeds, every name in `tasks` appears in the result exactly once. - A dependency pair may appear more than once; repeats mean the same as a single copy. - If tasks remain but none is ready, return `[]`. ### Constraints - `1 <= len(tasks) <= 10^4` - `0 <= len(dependencies) <= 5 * 10^4` - Task names are unique, 1 to 20 characters long, and contain only lowercase English letters, digits and `_`. - Each dependency is a list of two different names, both in `tasks`. ### Examples #### Example 1 ```text Input: tasks = ["build","deploy","test","lint"], dependencies = [["build","test"],["test","deploy"],["lint","deploy"]] Output: ["build","lint","test","deploy"] ``` `build` and `lint` have no prerequisites, and `build` is the smaller name. Once `build` is placed, `lint` and `test` are both ready and `lint` is smaller. `deploy` waits for both `test` and `lint`. #### Example 2 ```text Input: tasks = ["a","b","c"], dependencies = [["a","b"],["b","c"],["c","a"]] Output: [] ``` Each task waits for another task in the cycle, so none can start. #### Example 3 ```text Input: tasks = ["c","a","b"], dependencies = [] Output: ["a","b","c"] ``` With no dependencies every task is ready at once, so the tasks run in name order.

Overview: A practical coding problem about scheduling dependent tasks: given task names and prerequisite pairs, return a run order in which every task follows its prerequisites, breaking ties by name, or an empty list when a cycle makes scheduling impossible. It tests dependency graph processing and cycle detection.

Read the full Apple Machine Learning Engineer interview experience this question came from

A job scheduler receives a list of task names `tasks` and a list of dependencies `dependencies` between them. A dependency `[before, after]` means task `before` must finish before task `after` can start. Tasks run one at a time. Return the order in which to run all the tasks so that every task starts only after all of its prerequisites have finished. When several tasks are ready at the same time, run the one with the smallest name. If the dependencies contain a cycle, so that some tasks can never start, return an empty list. ### Rules - A task is ready when every task it depends on has already been placed in the order. A task with no prerequisites is ready from the start. - Whenever more than one task is ready, the next task is the smallest ready name under Python string comparison. For these names that means comparing character codes from left to right: digits come before `_`, and `_` comes before lowercase letters, so `"10"` comes before `"9"` and `"_x"` comes before `"a"`. When one name is a prefix of another, the shorter name comes first (`"a"` before `"ab"`). - When scheduling succeeds, every name in `tasks` appears in the result exactly once. - A dependency pair may appear more than once; repeats mean the same as a single copy. - If tasks remain but none is ready, return `[]`. ### Constraints - `1 <= len(tasks) <= 10^4` - `0 <= len(dependencies) <= 5 * 10^4` - Task names are unique, 1 to 20 characters long, and contain only lowercase English letters, digits and `_`. - Each dependency is a list of two different names, both in `tasks`. No count in this problem exceeds 2^31-1, so 32-bit integers are enough in every language. ### Input and output by language - Python and JavaScript receive `tasks` as a list of strings and `dependencies` as a list of two-element lists, and return a list of strings. - Java receives `java.util.List<String> tasks` and `java.util.List<java.util.List<String>> dependencies`, and returns a `java.util.List<String>`. - C++ receives `const std::vector<std::string>& tasks` and `const std::vector<std::vector<std::string>>& dependencies`, and returns a `std::vector<std::string>`. Names use only ASCII characters, so the default string ordering in JavaScript, Java and C++ matches Python string comparison. ### Examples #### Example 1 ```text Input: tasks = ["build","deploy","test","lint"], dependencies = [["build","test"],["test","deploy"],["lint","deploy"]] Output: ["build","lint","test","deploy"] ``` `build` and `lint` have no prerequisites, and `build` is the smaller name. Once `build` is placed, `lint` and `test` are both ready and `lint` is smaller. `deploy` waits for both `test` and `lint`. #### Example 2 ```text Input: tasks = ["a","b","c"], dependencies = [["a","b"],["b","c"],["c","a"]] Output: [] ``` Each task waits for another task in the cycle, so none can start.

Constraints

  • 1 <= len(tasks) <= 10^4
  • 0 <= len(dependencies) <= 5 * 10^4
  • Task names are unique, 1 to 20 characters long, and contain only lowercase English letters, digits and `_`.
  • Each dependency is a list of two different names, both in `tasks`.

Examples

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

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

Explanation: Example 1: build and lint start ready and build is smaller, then lint beats the newly ready test, and deploy waits for both test and lint.

Input: (['a', 'b', 'c'], [['a', 'b'], ['b', 'c'], ['c', 'a']])

Expected Output: []

Explanation: Example 2: the three tasks form one full cycle, so none can start.

Hints

  1. After each task is placed, look again at everything that is ready: a task that just became ready can have a smaller name than tasks that were waiting before it.
  2. A repeated dependency pair must not make a task wait any longer than a single copy would.
  3. If tasks remain but none of them is ready, the rules ask for an empty list, even when some tasks were already placed.

Schedule Dependent Tasks, Smallest Ready Name First

mediumAppleMachine Learning Engineer

A job scheduler receives a list of task names tasks and a list of dependencies dependencies between them. A dependency [before, after] means task before must finish before task after can start. Tasks run one at a time. Return the order in which to run all the tasks so that every task starts only after all of its prerequisites have finished.

When several tasks are ready at the same time, run the one with the smallest name. If the dependencies contain a cycle, so that some tasks can never start, return an empty list.

Rules

  • A task is ready when every task it depends on has already been placed in the order. A task with no prerequisites is ready from the start.
  • Whenever more than one task is ready, the next task is the smallest ready name under Python string comparison. For these names that means comparing character codes from left to right: digits come before _, and _ comes before lowercase letters, so "10" comes before "9" and "_x" comes before "a". When one name is a prefix of another, the shorter name comes first ("a" before "ab").
  • When scheduling succeeds, every name in tasks appears in the result exactly once.
  • A dependency pair may appear more than once; repeats mean the same as a single copy.
  • If tasks remain but none is ready, return [].

Constraints

  • 1 <= len(tasks) <= 10^4
  • 0 <= len(dependencies) <= 5 * 10^4
  • Task names are unique, 1 to 20 characters long, and contain only lowercase English letters, digits and _.
  • Each dependency is a list of two different names, both in tasks.

No count in this problem exceeds 2^31-1, so 32-bit integers are enough in every language.

Input and output by language

  • Python and JavaScript receive tasks as a list of strings and dependencies as a list of two-element lists, and return a list of strings.
  • Java receives java.util.List<String> tasks and java.util.List<java.util.List<String>> dependencies, and returns a java.util.List<String>.
  • C++ receives const std::vector<std::string>& tasks and const std::vector<std::vector<std::string>>& dependencies, and returns a std::vector<std::string>.

Names use only ASCII characters, so the default string ordering in JavaScript, Java and C++ matches Python string comparison.

Examples

Example 1

Input:  tasks = ["build","deploy","test","lint"], dependencies = [["build","test"],["test","deploy"],["lint","deploy"]]
Output: ["build","lint","test","deploy"]

build and lint have no prerequisites, and build is the smaller name. Once build is placed, lint and test are both ready and lint is smaller. deploy waits for both test and lint.

Example 2

Input:  tasks = ["a","b","c"], dependencies = [["a","b"],["b","c"],["c","a"]]
Output: []

Each task waits for another task in the cycle, so none can start.

Examples

Example 1
Input
(['build', 'deploy', 'test', 'lint'], [['build', 'test'], ['test', 'deploy'], ['lint', 'deploy']])
Output
['build', 'lint', 'test', 'deploy']
Notes
Example 1: build and lint start ready and build is smaller, then lint beats the newly ready test, and deploy waits for both test and lint.
Example 2
Input
(['a', 'b', 'c'], [['a', 'b'], ['b', 'c'], ['c', 'a']])
Output
[]
Notes
Example 2: the three tasks form one full cycle, so none can start.

Constraints

  • •1 <= len(tasks) <= 10^4
  • •0 <= len(dependencies) <= 5 * 10^4
  • •Task names are unique, 1 to 20 characters long, and contain only lowercase English letters, digits and `_`.
  • •Each dependency is a list of two different names, both in `tasks`.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def schedule_tasks(tasks: list[str], dependencies: list[list[str]]) -> list[str]:
Sample call
schedule_tasks(['build', 'deploy', 'test', 'lint'], [['build', 'test'], ['test', 'deploy'], ['lint', 'deploy']])
Language
Case 1
Input
(['build', 'deploy', 'test', 'lint'], [['build', 'test'], ['test', 'deploy'], ['lint', 'deploy']])
Expected
['build', 'lint', 'test', 'deploy']
Case 2
Input
(['a', 'b', 'c'], [['a', 'b'], ['b', 'c'], ['c', 'a']])
Expected
[]

Browse More Questions

Show the approach

Approach

Build, for every task, the list of tasks that depend on it and a count of the prerequisite pairs it is still waiting for. Every copy of a pair adds one to the count and one entry to the dependents list, so when the before task is placed each copy is removed again and repeated pairs behave like a single copy. Put every task whose count is zero into a min-priority queue ordered by name. Repeatedly remove the smallest name, append it to the result, and decrement the count of each of its dependents; a dependent whose count reaches zero joins the queue.

Invariant: the queue holds exactly the tasks that are ready and not yet placed. A task's count equals the number of pair copies whose before task is still unplaced, so it reaches zero exactly when all of its prerequisites are placed. The queue is consulted again after every single placement, so a task that becomes ready later with a smaller name runs ahead of tasks that were ready earlier, as the rules require. Processing ready tasks level by level would break this: tasks [a, z, b] with a before b must give [a, b, z].

If the queue empties while some task is unplaced, every unplaced task waits on another unplaced task, which only a cycle can cause, and the answer is [] even when some tasks were placed before the stall.

The JavaScript, Java and C++ references sort the names once and run the queue on each name's position in that sorted list, which yields the same order as comparing the strings. Edge cases: a single task, no dependencies (the result is the sorted names), repeated pairs, and a cycle in one component while other components are schedulable.

Time complexity:
O(V log V + E), where V = len(tasks) and E = len(dependencies)
Space complexity:
O(V + E)