Question
Given a list of packages that need to be built and the dependencies for each package, determine a valid order in which to build the packages.
eg.
0:
1: 0
2: 0
3: 1, 2
4: 3
output: 0, 1, 2, 3, 4
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video (Github):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// Perform topological sort // Input is a list of dependencies where the index is the process number // and the value is the numbers the processes it depends on public static List<Integer> buildOrder(int[][] processes) { Set<Integer> temporaryMarks = new HashSet<Integer>(); Set<Integer> permanentMarks = new HashSet<Integer>(); List<Integer> result = new LinkedList<Integer>(); // Recursively search from any unmarked node for (int i = 0; i < processes.length; i++) { if (!permanentMarks.contains(i)) { visit(i, processes, temporaryMarks, permanentMarks, result); } } return result; } // Search through all unmarked nodes accessible from process public static void visit(int process, int[][] processes, Set<Integer> temporaryMarks, Set<Integer> permanentMarks, List<Integer> result) { // Throw an error if we find a cycle if (temporaryMarks.contains(process)) throw new RuntimeException("Graph is not acyclic"); // If we haven't visited the node, recursively search from there if (!permanentMarks.contains(process)) { temporaryMarks.add(process); // Perform recursive search from children for (int i : processes[process]) { visit(i, processes, temporaryMarks, permanentMarks, result); } // Add permanent mark, remove temporary mark, and add to results list permanentMarks.add(process); temporaryMarks.remove(process); result.add(process); } } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.