Can you come up with solution? From Yandex interview

Implement a function with the following signature:

function makeSchedule(array $todo): array

The input array should be interpreted as a list of tasks to be done, together with
dependencies on other tasks, for example:

[
    0 => [1, 2],
    1 => [2, 3],
    2 => [3],
    3 => []
]

This should be interpreted as follows:

  • Task 0 should be performed only after tasks 1 and 2 are done.
  • Task 1 should be performed only after tasks 2 and 3 are done.
  • Task 2 should be performed only after task 3 is done.
  • Task 3 may be performed at any time.

The input array is guaranteed to be non-empty, and tasks are guaranteed to be
indexed from 0 to count($todo) - 1. Every element of the input array is also
guaranteed to be an array, all elements of each are guaranteed to be valid task
indices. You may assume that the input is always correct, so you do not need to
validate it.

The function should return an array listing the sequence of tasks in the order of
execution such that all the constraints provided as an input are satisfied. In
case this is impossible, the function should return an empty array. For example,
the input above enforces just a single possible sequence of task execution:

[3, 2, 1, 0]

Note that in some cases multiple different schedules may satisfy all the
constraints. E.g., for the following input:

[
    0 => [],
    1 => []
]

Both [0, 1] and [1, 0] are valid results, and both would be accepted by the
automated grader. A simple example of input containing constraints that cannot be
satisfied would be:

[
    0 => [1],
    1 => [0]
]

makeSchedule() should return an empty array when called with the above array as an
argument.

An efficient solution should be capable of processing a few hundred tasks with
several thousand dependencies (in total) in under a second.

Comments (1)