← Microsoft Interview InsightsSoftware Engineer
My first instinct was to just run Dijkstra from every node and call it done.
For each node v, remove v from the graph and compute the shortest path between every pair of its neighbors; the minimum cycle through v is the minimum over all neighbors u,w of dist(u,w) + weight(v,u) + weight(v,w). This can be done efficiently by running Dijkstra from each neighbor of v on the graph without v, or by using a modified all-pairs shortest path approach. Alternatively, run Dijkstra from each node and consider the shortest cycle formed by the two shortest paths from the source to each neighbor.
Pro tip: Mention that for dense graphs, Floyd-Warshall with cycle detection might be simpler, but for sparse graphs, repeated Dijkstra from each neighbor is more efficient; also note that handling negative weights requires Bellman-Ford, but typically weights are positive.
Confirm whether the graph is directed or undirected, weights are positive, and whether self-loops or multiple edges are allowed. Discuss handling of nodes with degree less than 2 (return 0).
A cycle through v must enter and leave v via two distinct edges (or the same edge if multigraph) and visit at least one other node. So it consists of two edge-disjoint paths from v to some node u, or equivalently a path between two neighbors of v that does not pass through v.
For each node v, remove v and run Dijkstra from each neighbor of v to find shortest paths to all other neighbors; the minimum cycle is the minimum sum of two such paths plus the connecting edges. Alternatively, run Dijkstra from each node s and for each edge (u,v) not in the shortest path tree, consider dist(s,u)+w(u,v)+dist(v,s) as a cycle through s.
Naive approach: O(n * (m log n + m)) using Dijkstra from each neighbor. For sparse graphs this is acceptable. For dense graphs, consider Floyd-Warshall O(n^3) and then for each v, find min over u,w of dist(u,w)+w(v,u)+w(v,w) with u,w != v. Discuss trade-offs.
Code the chosen algorithm, ensuring to handle disconnected graphs and nodes with no cycle. Test with small graphs, including cases with multiple edges and self-loops if allowed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.