← Questions
Shortest cycle through each node
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's HackerRank assessment, last asked Feb 2026. It tests graphs and shortest path.
You are given a directed graph with positive edge weights. For every node, return the cost of the cheapest cycle that passes through it, or -1 if no cycle passes through it.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
min_cycle_cost(n: int, edges: list[tuple[int, int, int]]) -> list[int]— nodes are0..n-1; each edge is(u, v, w)fromutovwith weightw.
Example
n = 5
edges = [(0, 1, 2), (1, 2, 3), (2, 0, 4), (1, 3, 1), (3, 1, 1), (2, 4, 5)]
min_cycle_cost(n, edges) -> [9, 2, 9, 2, -1]
# 0 and 2: 0->1->2->0 costs 9
# 1 and 3: 1->3->1 costs 2
# 4 has no outgoing edges
Constraints
-
1 <= n <= 1000,0 <= len(edges) <= 5000,1 <= w <= 10^5. - Self-loops and parallel edges may appear; a self-loop is a cycle of one edge.
Clarifying questions
- Is the graph directed? (Yes here; ask what changes if not.)
- Are weights positive?
- Do self-loops count as cycles?
- Must the cycle be simple, or may it repeat nodes?
What a strong answer covers
- The key identity: the cheapest cycle through
sismin over edges (u -> s, w)ofdist(s, u) + w, wheredistis the shortest path froms. - Running Dijkstra from every node: O(n * (m + n) log n) overall, fine for these limits.
- Why a cheapest closed walk through
sis also a simple cycle when weights are positive. - Handling self-loops, parallel edges and unreachable nodes.
- What changes for undirected graphs (an edge cannot be used straight back), and why it is harder.
Follow-ups
- Return the cycle itself for each node.
- Find only the single cheapest cycle in the whole graph more cheaply.
- Weights can be negative but there is no negative cycle.
- The graph is undirected.
Where it's asked
- Microsoft · HackerRank assessment · Last asked Feb 202690 min · Two problems in a locked full-screen browser
What it tests
graphs · shortest path
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
