FastPrepOrder Sources by Their Dependencies

Order Sources by Their Dependencies

Retool logoRetool● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You receive unique source names and dependency pairs. A pair [source, prerequisite] means that prerequisite must be processed before source.

Return an ordering containing every source exactly once and satisfying every dependency. When several sources are currently available, choose the lexicographically smallest name. This produces a deterministic smallest valid ordering.

If any cycle prevents completing all sources, return the one-element array ["IMPOSSIBLE"]. With no sources, return an empty array.

Function

sourceOrder(sources: String[], dependencies: String[][]) → String[]

Examples

Example 1

sources = ["app","lib","core","docs"]dependencies = [["app","lib"],["lib","core"]]return = ["core","docs","lib","app"]

Every prerequisite must appear first. Choose the lexicographically smallest currently available source, or report a cycle.

Example 2

sources = ["a","b"]dependencies = [["a","b"],["b","a"]]return = ["IMPOSSIBLE"]

Every prerequisite must appear first. Choose the lexicographically smallest currently available source, or report a cycle.

Example 3

sources = []dependencies = []return = []

Every prerequisite must appear first. Choose the lexicographically smallest currently available source, or report a cycle.

Constraints

  • 0 <= sources.length <= 1000.
  • Each unique source name has 1 to 20 lowercase English letters.
  • 0 <= dependencies.length <= 5000.
  • Every pair references supplied names, and dependency pairs are unique. Self-dependencies are allowed and form a cycle.

More Retool problems

See Retool hiring insights
public String[] sourceOrder(String[] sources, String[][] dependencies) {
    // Write your code here.
}
sources["app","lib","core","docs"]
dependencies[["app","lib"],["lib","core"]]
expected["core", "docs", "lib", "app"]
Checking account…