Google interview question

write code to find the second shortest path between two given nodes in an undirected graph.

Interview Answers

Anonymous

15 Nov 2010

First, solve the single-destination shortest path problem for target vertex t. The interview question specifies an undirected graph, so single-destination t is equivalent to single-source t. If it were a directed graph, reverse all edges and then apply Dijkstra's algorithm with target vertex t as the "source". Now walk along the shortest path from the source vertex s to the target vertex t. At each vertex v along this shortest path, consider taking a single step to the side by exploring all vertices x adjacent to v where x is not the next vertex on the shortest path. Calculate distance(s, v) + distance(v, x) + distance(x, t). Record the minimum value found. It will be the second shortest path. distance(s, v) can be summed incrementally as you walk away from s. distance(v, x) is the length of a single edge. distance(x, t) was calculated and stored in the first step for all vertices x. The rationale of this algorithm is to make only one "misstep" along the path from s to t. After making the misstep, follow the new optimum path to t. Choose the misstep that minimizes the cost of the error. The misstep could even be a single step backwards along the shortest path.

5

Anonymous

17 Jan 2011

Crv, I think you are not right, it is not proven anything in what you said.

3

Anonymous

2 Nov 2010

I can think of two solutions. Say s is source node and t is target node. 1. Find shortest path from s to t using Dijkstra's algo. In this algo, when all nodes are being visited, a node at a shortest distance from source so far is chosen to proceed. When you make this selection, you should also store the value of the second best distance. So before overwriting smallestDistance, also store its discarded value in say secondSmallestDistance. Do this only when the node in consideration is the target node. At the end, you would have second shortest distance. Have a similar approach to record path of this second shortest distance. 2. Find shortest distance from source to all nodes that have a direct arc to target node. Add up the node to target distance in each and find the second shortest.

4

Anonymous

17 Jan 2011

http://hatemabdelghani.wordpress.com/2009/07/04/second-shortest-path/ Here you can find the shortests paths between ant 2 nodes. This can be used for a particular case I guess (e.g. for Dijkstra). Its running time is O(n ^ 3).

1