← Questions

Shortest cycle through each node

0
MicrosoftCodingLast asked Feb 2026

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 are 0..n-1; each edge is (u, v, w) from u to v with weight w.

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 s is min over edges (u -> s, w) of dist(s, u) + w, where dist is the shortest path from s.
  • Running Dijkstra from every node: O(n * (m + n) log n) overall, fine for these limits.
  • Why a cheapest closed walk through s is 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

What it tests

graphs · shortest path

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