Question
Given a directed graph, find the shortest path between two nodes if one exists.
eg.
Directed graph:
shortestPath(2, 3) = 2 -> 5 -> 4 -> 3
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
// Graph node class public static class Node { int value; List<Node> children; // Basic constructor public Node(int value) { this.value = value; } // Lazily instantiate children list public void addChild(Node n) { if (this.children == null) this.children = new LinkedList<Node>(); this.children.add(n); } } // Find the shortest path between two nodes using BFS public static List<Node> shortestPath(Node a, Node b) { // Return null if either node is null or if they're the same node if (a == null || b == null) return null; if (a == b) return null; // Using a queue for our BFS Queue<Node> toVisit = new LinkedList<Node>(); // Track the parents so that we can reconstruct our path HashMap<Node, Node> parents = new HashMap<Node, Node>(); // Initialize the BFS toVisit.add(a); parents.put(a, null); // Keep going until we run out of nodes or reach our destination while (!toVisit.isEmpty()) { Node curr = toVisit.remove(); // If we find the node we're looking for then we're done if (curr == b) break; // If the current node doesn't have children, skip it if (curr.children == null) continue; // Add all the children to the queue for (Node n : curr.children) { if (!parents.containsKey(n)) { toVisit.add(n); parents.put(n, curr); } } } // If we couldn't find a path, the destination node won't have been // added to our parents set if (parents.get(b) == null) return null; // Create the output list and add the path to the list List<Node> out = new LinkedList<Node>(); Node n = b; while (n != null) { out.add(0, n); n = parents.get(n); } return out; } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.