Scrivio Interview library
Graph algorithmsGraphsReported 17 times · 16 min read · updated 15 November 2026

Given modules and their dependencies, find an order in which they can be executed.

1What it means to put the modules in a safe order

Think about getting dressed in the morning. Socks must go on before shoes, a shirt before a tie, and trousers before a belt. Some pairs have no rule at all between them, because you can put on your watch before or after your shirt and nobody minds. Each garment has a few others that must already be on, and that small, familiar puzzle is exactly our problem.

In this question the garments are modules, pieces of a program such as a database layer or a login service. For each module we are told which other modules it depends on, which means those others must run first. Our job is to hand back one order of all the modules in which every module appears after everything it depends on.

Let us keep one example for the whole article. There are five modules. ui depends on app. app depends on db and auth. auth depends on db and config. db depends on config. config depends on nothing at all. The picture shows them with what each one needs.

PictureThe five modules and what each one needs

Each box is a module, in the order the input lists them. The panel says which modules must run before each one.

  1. ui0app1auth2db3config4
    ui needs
    app
    app needs
    db, auth
    auth needs
    db, config
    db needs
    config
    config needs
    nothing

    1Five modules, listed as the input gives them. config is marked because it needs nothing, so it is the only module that can run first.

What to assume

What if the dependencies go round in a circle, so that a needs b and b needs a?
Then no order exists, and we return an empty list.
What about a module that appears only as somebody's dependency?
It is treated as one that needs nothing.
How large can the input be?
Tens of thousands of modules, so we want work that grows in step with its size.

Now let us find an order by hand. Which module can run first? Only one that needs nothing, and that is config. Once config has run, look again. db needed only config, so db can run now. auth needed db and config, and both have run, so auth is next. app needed db and auth, both done, so app runs. Last comes ui, which needed app. Our order is config, db, auth, app, ui. Here only one order works, but in general there can be many, as with the watch and the shirt, and any valid one is accepted. At every step we looked for a module whose needs were all met already. Keep that habit in mind, because the whole solution grows out of it.

A careful candidate asks first what happens if the dependencies go round in a circle, so that a needs b and b needs a. Then no order exists, and we agree to return an empty list. A module that appears only as somebody's dependency is treated as one that needs nothing. The input may hold tens of thousands of modules, so we want work that grows in step with its size.

2How to recognise an ordering problem hiding in a graph

Reading this question for the first time, the word order makes many beginners think of sorting. Perhaps we could give every module a number and sort by it? But to choose the numbers we would already need the answer, and sorting needs a rule that compares any two items, while two modules may have no rule between them at all, like the watch and the shirt. So ordinary sorting is the wrong tool.

So let us read the question slowly and take the clues one at a time. The first clue is the word dependencies. A dependency is a relation between two things, one that must come before another. Things joined by relations between pairs can be drawn as a graph. A graph, in everyday words, is a set of dots joined by lines. Here each module is a dot, called a node, and each dependency is a line, called an edge.

The second clue is that the relation has a direction. config must come before db, not the other way round, so we draw each edge as an arrow, from the module that must run first to the module that waits for it. A graph whose edges are arrows is called a directed graph. Our example has six arrows, config to db, config to auth, db to auth, db to app, auth to app and app to ui.

The third clue is the word order, asking for all the modules in a line. Together the clues point to the graph algorithms pattern, and to one algorithm in it called a topological sort. Topological here simply means it respects the shape of the arrows. A topological order is a line of all the nodes in which every arrow points forward, from left to right. Such an order exists exactly when you cannot follow arrows from some node and come back to it, which is called having no cycle. The rule to carry to new problems is this. When items must come before other items, draw arrows from each prerequisite to what needs it, and ask for a topological order.

Some graph tools look similar but do not fit. Breadth-first search from one node finds shortest routes, not a line of every node that respects the arrows. Union-find, which groups connected items, spots cycles only in graphs whose lines have no direction.

3The honest first attempt, sweeping the list until everything has run

Before looking for anything clever, let us write down the method we used by hand, because it is correct and it is how most people start. We keep a set of modules that have already run and sweep down the whole list, running any module whose dependencies have all run, then sweep again from the top. We stop when every module has run, or when a whole sweep runs nothing, because then the remaining modules must be waiting on each other in a circle.

Step throughRepeated sweeps look at the same waiting modules again and again

Each frame is one full sweep down the list. Compared modules were looked at and still wait; the marked module runs in that sweep.

  1. ui0app1auth2db3config4
    sweep
    1
    done
    config
    looks so far
    5

    1Sweep 1 looks at ui, app, auth and db, and each still waits for something. Only config, the last module, can run.

  2. ui0app1auth2db3config4
    sweep
    2
    done
    config, db
    looks so far
    9

    2Sweep 2 starts again at the top. ui, app and auth still wait, and db can run now that config is done.

  3. ui0app1auth2db3config4
    sweep
    3
    done
    config, db, auth
    looks so far
    12

    3Sweep 3 looks at ui and app again for nothing, and runs auth, whose two dependencies are now done.

  4. ui0app1auth2db3config4
    sweep
    4
    done
    config, db, auth, app
    looks so far
    14

    4Sweep 4 looks at ui a fourth time, still waiting, and runs app.

  5. ui0app1auth2db3config4
    sweep
    5
    done
    all five
    looks so far
    15

    5Sweep 5 finally runs ui. Fifteen looks placed five modules, and ui alone was examined five times.

Java
// Brute force: sweep all modules again and again, running any whose dependencies are done.
static List<String> order(Map<String, List<String>> deps) {
List<String> result = new ArrayList<>();
Set<String> done = new HashSet<>();
boolean progress = true;
while (progress && done.size() < deps.size()) { // stop when a sweep runs nothing
progress = false;
for (var e : deps.entrySet()) {
if (!done.contains(e.getKey()) && done.containsAll(e.getValue())) {
done.add(e.getKey()); // every dependency has run
result.add(e.getKey());
progress = true;
}
}
}
return done.size() == deps.size() ? result : List.of(); // stuck: a cycle
}

Let us run it on our example and count the looks. In the first sweep ui waits for app, app waits for db, auth waits for db, db waits for config, and only config, the last one, can run. That is five looks to run one module. The second sweep looks at the four modules still waiting and runs only db. The third looks at three and runs auth, the fourth looks at two and runs app, and the fifth looks at ui alone and runs it.

Now we count. The sweeps looked at 5 + 4 + 3 + 2 + 1 = 15 modules, with 17 dependency checks, to place 5 modules. In general, if there are V modules and E dependencies, one sweep costs about V + E steps, and in the worst case, as here, each sweep places only one module, so we need V sweeps. The time grows like V times (V + E), far too slow for ten thousand modules. The extra space is only the set of finished modules, O(V).

So where exactly is the waste? Look at ui. It was examined in every one of the five sweeps, and four times the answer was the same, it waits for app. Yet a module's situation can only change at one moment, when one of the modules it depends on finishes. The brute force keeps asking a question whose answer it already knows.

4Getting to Kahn's algorithm, one observation at a time

What would it take to know when a module is ready without asking? Think of the morning again. Suppose next to each garment you wrote how many other garments must be on before it. Shoes would carry a 1, for socks. Each time you put something on, you would lower the number on every garment waiting for it, and the moment a number reaches zero, that garment is ready. You never look at it in between.

That number has a name in graph language. The count of arrows coming into a node is its in-degree, here the number of dependencies a module still waits for. On the example, ui starts at 1, app at 2, auth at 2, db at 1 and config at 0. To lower the right counts quickly, we also need, for each module, the list of modules that wait for it. We call them its dependents. config's dependents are auth and db, db's are app and auth, auth's is app, and app's is ui.

Now the method almost writes itself. Every module whose count is zero is ready, so we put it in a queue, a waiting line where the first to join is the first to leave. Then we repeat one step. Take the module at the front of the queue and add it to the result. Go through its dependents and lower each one's count by one, because one of its dependencies has just been met. If a count reaches zero, that module joins the queue. This method is called Kahn's algorithm.

A beginner usually asks a fair question here. Why wait for the count to reach zero? Would it not be quicker to add a module as soon as one of its dependencies finishes? Let us try it on auth and see. When config finishes, auth's count drops from 2 to 1. If we added auth to the queue then, it could run before db, yet auth needs db. The count protects us, because it reaches zero only after every dependency has been placed in the result. That is also why the whole result is correct, since every arrow then points forward.

Step throughA cycle never lets any count reach zero

Three modules that need each other in a circle: a needs b, b needs c, and c needs a.

  1. a0b1c2
    counts
    a 1, b 1, c 1
    ready queue
    empty
    result
    []

    1Each of a, b and c waits for one other module, so every count starts at 1 and the ready queue starts empty.

  2. a0b1c2
    counts
    a 1, b 1, c 1
    ready queue
    empty
    result
    [] (0 of 3)

    2The loop never runs, so the result holds 0 of the 3 modules. The sizes differ, which tells us there is a cycle, and we return an empty list.

And what happens with a cycle? In the small picture above, a needs b, b needs c and c needs a. Every count starts at 1, so nobody is ready and the queue starts empty. Modules on a cycle each wait for another module of the same cycle, so their counts never fall to zero. When the queue runs dry, we compare the size of the result with the number of modules. If they are equal, every module was placed. If the result is shorter, some modules were stuck on a cycle and no order exists, so we return an empty list.

5Watching the counts fall on the five modules

The picture plays Kahn's algorithm on our five modules exactly as the Java program runs it. Watch the counts in the panel. Every time a module is taken from the queue, the counts of its dependents fall by one, and a module joins the ready queue only at the moment its count becomes 0.

The module being taken is marked, dependents whose counts are lowered are shown as compared, and placed modules are shown as finished.

Step throughKahn's algorithm on the five modules

The counts are the unmet dependencies of each module. A module joins the ready queue the moment its count falls to 0.

  1. ui0app1auth2db3config4
    counts
    ui 1, app 2, auth 2, db 1, config 0
    ready queue
    config
    result
    []

    1We count each module's unmet dependencies. Only config has a count of 0, so it is the only module in the ready queue.

  2. ui0app1auth2db3config4
    counts
    ui 1, app 2, auth 2, db 1, config 0
    ready queue
    empty
    result
    [config]

    2We take config from the front of the queue and add it to the result. Its dependents are auth and db.

  3. ui0app1auth2db3config4
    counts
    ui 1, app 2, auth 1, db 0, config 0
    ready queue
    db
    result
    [config]

    3Lowering their counts, auth falls from 2 to 1 and still waits, while db falls from 1 to 0 and joins the queue.

  4. ui0app1auth2db3config4
    counts
    ui 1, app 1, auth 0, db 0, config 0
    ready queue
    auth
    result
    [config, db]

    4We take db. Its dependents are app and auth. app falls from 2 to 1, and auth falls from 1 to 0 and joins the queue.

  5. ui0app1auth2db3config4
    counts
    ui 1, app 0, auth 0, db 0, config 0
    ready queue
    app
    result
    [config, db, auth]

    5We take auth. Its only dependent is app, which falls from 1 to 0, so app joins the queue with both its needs met.

  6. ui0app1auth2db3config4
    counts
    ui 0, app 0, auth 0, db 0, config 0
    ready queue
    ui
    result
    [config, db, auth, app]

    6We take app. Its only dependent is ui, which falls from 1 to 0 and joins the queue.

  7. ui0app1auth2db3config4
    counts
    ui 0, app 0, auth 0, db 0, config 0
    ready queue
    empty
    result
    [config, db, auth, app, ui]

    7We take ui. No module depends on ui, so no count changes, and the queue is now empty.

  8. ui0app1auth2db3config4
    counts
    all 0
    ready queue
    empty
    result
    [config, db, auth, app, ui]
    placed
    5 of 5

    8The loop ends. The result holds all 5 modules, the same as the number of modules, so no cycle exists and we return the order.

Let us read the important frames back. In the second and third frames, config is taken and both auth and db are lowered, but only db reaches 0. This is where adding auth early would have been a mistake. In the fourth frame db is taken, and now auth reaches 0, because both of its dependencies are in the result.

Notice also how little work each module caused. ui was touched exactly once, when app finished, instead of five times as in the sweeps. Every arrow in the graph was followed exactly once, at the moment the module it starts from was taken from the queue. Six arrows, six lowered counts. That is the whole saving.

In the last frame we compare 5 placed modules with 5 in all; a shorter result would have meant a cycle.

6The complete Java program

Here is the complete program. The input is a LinkedHashMap, a map that remembers the order in which keys were added, so the program prints the same order on every run. main runs our example, a three-module cycle and an empty input.

Java
import java.util.*;
public class BuildOrder {
// deps maps each module to the modules it depends on (they must run before it).
// Returns a valid order, or an empty list if the dependencies contain a cycle.
static List<String> order(Map<String, List<String>> deps) {
Map<String, Integer> waiting = new LinkedHashMap<>(); // unmet dependencies per module
Map<String, List<String>> dependents = new HashMap<>(); // edge: dependency -> module
for (var e : deps.entrySet()) {
waiting.putIfAbsent(e.getKey(), 0);
for (String d : e.getValue()) {
waiting.putIfAbsent(d, 0); // a dependency may have no entry
waiting.merge(e.getKey(), 1, Integer::sum);
dependents.computeIfAbsent(d, k -> new ArrayList<>()).add(e.getKey());
}
}
Deque<String> ready = new ArrayDeque<>();
waiting.forEach((m, count) -> { if (count == 0) ready.add(m); });
List<String> result = new ArrayList<>();
while (!ready.isEmpty()) {
String m = ready.poll();
result.add(m); // m can run now
for (String next : dependents.getOrDefault(m, List.of())) {
if (waiting.merge(next, -1, Integer::sum) == 0) ready.add(next); // last dependency met
}
}
return result.size() == waiting.size() ? result : List.of(); // leftovers mean a cycle
}
public static void main(String[] args) {
Map<String, List<String>> deps = new LinkedHashMap<>();
deps.put("ui", List.of("app"));
deps.put("app", List.of("db", "auth"));
deps.put("auth", List.of("db", "config"));
deps.put("db", List.of("config"));
deps.put("config", List.of());
System.out.println(order(deps)); // [config, db, auth, app, ui]
Map<String, List<String>> cycle = new LinkedHashMap<>();
cycle.put("a", List.of("b"));
cycle.put("b", List.of("c"));
cycle.put("c", List.of("a"));
System.out.println(order(cycle)); // []
System.out.println(order(Map.of())); // []
}
}

Let us read order in the order it runs. First we build two maps. waiting holds the counts, and dependents holds the arrows. For each module we call putIfAbsent with 0, so a module that needs nothing still gets a count. Then, for every dependency d, we call putIfAbsent on d as well, because a dependency might never have a line of its own.

Inside the same loop, merge with 1 adds one to the module's count, storing 1 if it had none, and computeIfAbsent fetches the dependents list of d, creating it the first time, and adds the module to it. That line draws the arrow from d to the module.

Next we fill the queue. ready is an ArrayDeque, Java's ready-made queue, and we add every module whose count is 0. The while loop then runs as long as some module is ready. poll removes the module at the front, and we add it to result because it can run now. For each of its dependents, merge with -1 lowers the count and returns the new value, so in one line we both lower it and test whether it reached 0. Only then does that dependent join the queue.

The last line is the cycle check. If result holds as many modules as waiting does, every module was placed and we return result. Otherwise some modules never reached 0, and we return List.of(), an empty list. A tempting slip is to skip this check. When only part of the graph is a cycle, the program would then hand back a partial order that silently leaves modules out.

7How much it costs, and the cases at the edges

Let us count on the example first. Building the maps visited 5 modules and 6 dependencies. The main loop took each of the 5 modules from the queue once and lowered a count 6 times, once per arrow. Compare that with 15 looks and 17 checks for the sweeps. In general, with V modules and E dependencies, building costs O(V + E) and the loop costs O(V + E), because each module enters the queue at most once and each arrow is followed once. The total is O(V + E), and we cannot do better, since we must at least read every dependency.

The space is also O(V + E). The counts, queue and result hold at most V entries each, and the dependents lists hold E entries in all.

Comparing the ways to order the modules
ApproachTimeExtra spaceFinds cycles?
Repeated sweeps over all modulesO(V (V + E))O(V)yes, when a sweep runs nothing
Kahn's algorithm with counts and a queueO(V + E)O(V + E)yes, leftover modules
Depth-first search, reverse finishing orderO(V + E)O(V + E)yes, with three colours

The edge cases need little special code. An empty input builds empty maps, the loop never runs, and 0 equals 0, so we return an empty list, as main shows. A cycle, including a module that lists itself as its own dependency, leaves some counts above zero, and we return an empty list. A dependency with no entry of its own gets a count of 0 from putIfAbsent and is ready at once. A module with no dependencies and no dependents is simply ready at the start.

A dependency listed twice by one module raises its count by two, but both copies of the arrow lower it again, so it still reaches 0 at the right moment.

8Follow-up questions

How would you solve it with depth-first search instead?

Depth-first search follows one path as deep as it goes before backing up. From each unvisited module we visit its dependencies first, and only after all of them are finished do we add the module itself to the result. To find cycles we mark each module as unvisited, on the current path, or finished, and reaching a module that is on the current path means a cycle. It is also O(V + E), but the recursion can overflow the call stack on a very long chain of dependencies.

Which modules could run at the same time?

Kahn's algorithm can answer this with a small change. Instead of taking modules one at a time, we take everything that is in the queue at once and call it one stage. All modules in a stage are ready together, so they can run in parallel. The number of stages equals the length of the longest chain of dependencies, which is the shortest possible time if every module takes one unit and there are enough workers.

What if the interviewer wants the alphabetically smallest valid order?

We replace the plain queue with a priority queue, a structure that always hands back the smallest item it holds, which Java provides as PriorityQueue. Whenever several modules are ready, the smallest name is taken first. Each insertion and removal now costs about log V steps instead of one, so the time becomes O(V log V + E).

9Conclusion

We ordered the modules by drawing each dependency as an arrow and counting, for every module, the dependencies it still waits for. A module with a count of zero is ready; taking it lowers the counts of its dependents, and a module joins the queue only when its count reaches zero. If the queue empties before every module is placed, there is a cycle. It costs O(V + E) time and space. The clue to remember is items that must come before other items: draw the arrows and ask for a topological order.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me first confirm the details. Each module lists the modules it depends on, I return any valid order, and if the dependencies form a cycle I return an empty list.

Then, if they want more

I will model this as a directed graph, with an arrow from each dependency to the module that needs it, and find a topological order.

A simple approach is to sweep the module list repeatedly and run anything whose dependencies are done, but that can take V sweeps, so it is O(V times (V + E)), and most of that time re-checks modules that have not changed. Instead I will use Kahn's algorithm.

In one pass I build, for each module, a count of unmet dependencies and a list of its dependents. Every module with count zero goes into a queue. I repeatedly take a module from the queue, append it to the result and decrement each dependent's count, adding a dependent to the queue when its count reaches zero.

A module is placed only after all its dependencies, so the order is valid. Modules on a cycle never reach zero, so if the result is shorter than the module count I return an empty list. That is O(V + E) time and O(V + E) space.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 17 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Given modules and their dependencies, find an order in which they can be executed.": https://scrivio-interview-library.netlify.app/data-structures/solutions/given-modules-and-their-dependencies-find-an-order-in-which-they-13884a/