Single-Edge Cycle Removal in Pod Dependencies
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A cluster orchestrator deploys n service pods numbered 0 through n - 1. Each entry [u, v] in edges specifies a directed prerequisite rule (u -> v): pod u must complete startup before pod v can launch.
Implement detect_cycle_and_break(n, edges) to return a dictionary with two keys:
"has_cycle"(bool): ReturnTrueif at least one directed cycle prevents allnpods from completing startup, orFalseif a valid startup sequence exists for every pod."edge"(Optional[List[int]]):- When
"has_cycle"isFalse, returnNone. - When
"has_cycle"isTrue, return[u, v]for a single entry inedgeswhose removal eliminates all cycles from the dependency graph. - Whenever a cyclic graph is given, you may assume at least one single edge index in
edgeseliminates every cycle when removed. If multiple indices inedgeseach leave the graph completely acyclic upon removal, return the one at the smallest index inedges.
- When
Examples
Example 1
Input: n = 4, edges = [[0, 2], [2, 3], [3, 2], [0, 1]]
Output: {"has_cycle": True, "edge": [2, 3]}
Explanation: Pods 2 and 3 deadlock each other via 2 -> 3 -> 2 (removing [0, 2] leaves that loop intact). Dropping either [2, 3] (index 1) or [3, 2] (index 2) yields a valid startup order, and [2, 3] appears earlier in edges.
Example 2
Input: n = 4, edges = [[0, 2], [1, 2], [2, 3]]
Output: {"has_cycle": False, "edge": None}
Explanation: Pods 0 and 1 can launch first, followed by 2 and then 3. No circular dependency exists.
Example 3
Input: n = 2, edges = [[0, 1], [1, 1]]
Output: {"has_cycle": True, "edge": [1, 1]}
Explanation: Self-prerequisite [1, 1] forms a single-edge cycle on pod 1. Removing [1, 1] leaves 0 -> 1, which is acyclic.
Example 4
Input: n = 5, edges = [[1, 2], [2, 3], [3, 1], [3, 4], [0, 1]]
Output: {"has_cycle": True, "edge": [1, 2]}
Explanation: Upstream pod 0 feeds into the three-pod loop 1 -> 2 -> 3 -> 1, while pod 4 waits downstream of pod 3. Removing [1, 2] at index 0 breaks the loop and allows startup order 0, 2, 3, 1, 4.
Constraints
1 <= n <= 20000 <= len(edges) <= 10^40 <= u, v < nfor every[u, v]inedges.- Self-loops (
u == v) and duplicate[u, v]entries may occur (removing one index deletes only that single occurrence, leaving any duplicate copies in place).
Step-by-step walkthrough
Understand the dependency graph and output contract
We have
nsoftware pods labeled0throughn - 1, and a list of directed dependency edges[u, v]meaning podumust be built before podv(u -> v).We need to answer two questions in a single dictionary:
has_cycle(bool): Does the graph contain any directed cycle? If yes, pods in that loop wait on each other forever, so building all pods is impossible.edge([u, v]orNone): If there is no cycle, returnNone. If there is a cycle, return one single edge[u, v]whose removal makes the entire graph cycle-free.
Three subtle details are worth nailing down right away:
- Deterministic tie-breaking: Several different edges might fix the graph. In Example 1 (
edges = [[0, 2], [2, 3], [3, 2], [0, 1]]), removing either[2, 3]or[3, 2]breaks the cycle, and the automated judge expects[2, 3]— the earliest valid edge in the input list. Checking candidates in increasing index order matches the judge every time. - Self-loops count: An edge
[v, v]("podvdepends on itself") is a 1-edge cycle (Example 3). - Duplicate edges can exist: If
[0, 1]appears twice inedges, removing just one copy still leaves the second copy in place! That is why we always identify edges by their list index0..len(edges) - 1, never just by the(u, v)pair.
Start with brute force and see what to optimize
What is the simplest correct algorithm?
- Check whether the full graph is already cycle-free. If so, return
{"has_cycle": False, "edge": None}. - Otherwise, loop
edge_idxfrom0tom - 1(wherem = len(edges)), temporarily ignoreedges[edge_idx], and check whether the remaining graph is cycle-free. Return the first edge that works.
Checking whether a graph has a cycle takes
O(n + m)time, so testing allmedges takesO(m * (n + m))time. In a dense dependency graph,mcan be close ton^2, makingmfull re-checks slow (O(n^3)). Can we shrink the candidate list frommedges down to at mostnedges?- Check whether the full graph is already cycle-free. If so, return
Detect cycles iteratively with Kahn's algorithm
First, let's build a rock-solid cycle checker using Kahn's algorithm (iterative topological sort). Unlike recursive depth-first search, Kahn's algorithm never hits Python's recursion limit on deep chains of thousands of pods.
How does Kahn's algorithm work? Count each pod's
indegree— how many prerequisites point into it. Any pod withindegree == 0can be built immediately! Pop a ready pod from a queue, mark it built, subtract1from theindegreeof every pod waiting on it, and enqueue any neighbor whoseindegreedrops to0.When the queue runs empty:
- If every pod was built, the graph has no cycle.
- Otherwise, the unbuilt pods (
is_stuck[pod] == True) are stuck waiting — either because they sit directly on a cycle, or because they sit downstream of a cycle:
Example 4: edges = [(1, 2), (2, 3), (3, 1), (3, 4), (0, 1)] 0 ---> 1 ---> 2 ^ | | v +----- 3 ---> 4 Initial indegrees: pod 0: 0, pod 1: 2, pod 2: 1, pod 3: 1, pod 4: 1 Pod 0 builds first, leaving pods 1, 2, 3, 4 with is_stuck == True. Notice pod 4 is stuck too, even though edge (3, 4) is NOT on the cycle!By adding a
skip_edge_idxparameter (-1keeps all edges), this single helper handles both Part 1 and candidate verification in Part 2:from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def find_stuck_pods(n: int, edges: List[List[int]], skip_edge_idx: int) -> List[bool]: """Run Kahn's topological sort ignoring `edges[skip_edge_idx]` (-1 keeps all edges). Returns is_stuck[pod] == True for every pod that can never be built. """ # indegree[pod]: number of unbuilt prerequisite edges currently pointing into `pod` indegree = [0] * n # out_neighbors[u]: list of pods `v` that directly depend on `u` (edges u -> v) out_neighbors = [[] for _ in range(n)] for edge_idx in range(len(edges)): if edge_idx == skip_edge_idx: continue u, v = edges[edge_idx] out_neighbors[u].append(v) indegree[v] += 1 # ready_queue: pods with 0 remaining prerequisites, ready to build immediately ready_queue = deque() for pod in range(n): if indegree[pod] == 0: ready_queue.append(pod) # is_stuck[pod]: starts True and flips to False as soon as `pod` gets built is_stuck = [True] * n while ready_queue: built_pod = ready_queue.popleft() is_stuck[built_pod] = False for dependent_pod in out_neighbors[built_pod]: indegree[dependent_pod] -= 1 if indegree[dependent_pod] == 0: ready_queue.append(dependent_pod) return is_stuckKey insight: an all-cycle breaker must lie on ANY one cycle
Suppose removing a single edge
eleaves the graph completely cycle-free. Could there have been any cycle in the original graph that did not usee? No — if a cycle didn't containe, deletingewouldn't touch that cycle at all, so that cycle would still survive!Therefore, any edge that breaks all cycles must belong to every cycle in the graph. That gives us two huge payoffs:
- We only need to find one simple cycle
Cin the graph. Every valid answer edge is guaranteed to be one ofC's edges (at mostnedges instead ofm!). - We still must test each edge of
C, becauseCcan also contain edges that belong only toCand miss another overlapping cycle:
Two overlapping cycles sharing edge (0, 1): Cycle A: 0 -> 1 -> 2 -> 0 Cycle B: 0 -> 1 -> 0 (shortcut 1 -> 0) +---(1, 0)---+ v | 0 ---(0, 1)-> 1 ---(1, 2)---> 2 ^ | +-----------(2, 0)------------+ Suppose we extract Cycle A = [(0, 1), (1, 2), (2, 0)]: - Remove (1, 2)? Cycle B (0 -> 1 -> 0) STILL survives! Not valid. - Remove (0, 1)? Both Cycle A and Cycle B break! Valid answer.- We only need to find one simple cycle
Extract one simple cycle by walking backward among stuck pods
How do we extract one simple cycle from
is_stuck? Look again at Example 4 (1 -> 2 -> 3 -> 1, upstream0 -> 1, and downstream3 -> 4):- If we start at stuck pod
4and try walking forward (u -> v), we immediately hit a dead end because pod4has zero outgoing edges! - What if we walk backward (
v <- u, following incoming prerequisites) instead? Why can a backward walk among stuck pods never hit a dead end?
Because every non-stuck pod was already built and subtracted from
indegreeduring Kahn's algorithm! If a podvis still stuck, its remainingindegreeis at least1, which guarantees at least one incoming edgeu -> vwhereuis also stuck.So we record one stuck-to-stuck incoming edge
incoming_edge_idx[v]for every stuck podv, pick any stuck starting pod, and step backward (current_pod -> prev_pod). Because there are at mostnpods, within at mostn + 1steps we must revisit some podw. Slicing the walk fromw's first visit drops any dead-end tail we started on (like4 <- 3) and leaves a pure simple cycle:Backward walk if starting at stuck pod 4 in Example 4: Step 0: at pod 4, follow incoming edge (3 -> 4) back to pod 3 walk = [(3,4)] Step 1: at pod 3, follow incoming edge (2 -> 3) back to pod 2 walk = [(3,4), (2,3)] Step 2: at pod 2, follow incoming edge (1 -> 2) back to pod 1 walk = [(3,4), (2,3), (1,2)] Step 3: at pod 1, follow incoming edge (3 -> 1) back to pod 3 walk = [(3,4), (2,3), (1,2), (3,1)] ^^^^^ pod 3 was first visited at Step 1! Slice walk[1:] -> [(2,3), (1,2), (3,1)] -> pure cycle 1 -> 2 -> 3 -> 1 (tail (3,4) trimmed!)Here is
extract_one_cycle:def extract_one_cycle(n: int, edges: List[List[int]], is_stuck: List[bool]) -> List[int]: """Return the edge indices of one simple directed cycle by walking backward among stuck pods.""" # Every stuck pod `v` still had indegree > 0 after all buildable pods were removed, # so `v` is guaranteed to have at least one incoming edge `u -> v` from another stuck pod `u`. # incoming_edge_idx[v]: index in `edges` of one stuck -> stuck edge entering `v`, or -1 incoming_edge_idx = [-1] * n for edge_idx in range(len(edges)): u, v = edges[edge_idx] if is_stuck[u] and is_stuck[v] and incoming_edge_idx[v] == -1: incoming_edge_idx[v] = edge_idx current_pod = is_stuck.index(True) # visit_step[pod]: index in `walk_edges` when `pod` was first visited, or -1 if unvisited visit_step = [-1] * n # walk_edges: edge indices followed backward (v <- u) until a pod repeats walk_edges = [] while visit_step[current_pod] == -1: visit_step[current_pod] = len(walk_edges) edge_idx = incoming_edge_idx[current_pod] prev_pod = edges[edge_idx][0] walk_edges.append(edge_idx) current_pod = prev_pod # Slicing from `visit_step[current_pod]` drops any lead-in tail walked before entering the cycle. cycle_start = visit_step[current_pod] return walk_edges[cycle_start:]- If we start at stuck pod
Test candidate edges in input order
Now
detect_cycle_and_breakbrings all three pieces together:- Run
find_stuck_pods(n, edges, skip_edge_idx=-1). Ifnot any(is_stuck), there is no cycle. - Otherwise, extract one simple cycle, sort its edge indices so earlier input edges come first, and return the first candidate whose removal leaves zero stuck pods.
def detect_cycle_and_break(n: int, edges: List[List[int]]) -> Dict[str, object]: # Phase 1: check whether the full graph (skip_edge_idx = -1) has any unbuildable pods. is_stuck = find_stuck_pods(n, edges, skip_edge_idx=-1) if not any(is_stuck): return {"has_cycle": False, "edge": None} # Phase 2: any single edge whose removal breaks ALL cycles must belong to EVERY cycle, # so it must appear among the edges of the one simple cycle we extract here. # Sorting indices tests candidates in original input order for deterministic tie-breaking. candidate_edge_indices = sorted(extract_one_cycle(n, edges, is_stuck)) for edge_idx in candidate_edge_indices: stuck_after_removal = find_stuck_pods(n, edges, skip_edge_idx=edge_idx) if not any(stuck_after_removal): u, v = edges[edge_idx] return {"has_cycle": True, "edge": [u, v]} # Fallback if the graph violates the one-edge-fix assumption (e.g., two disjoint cycles). return {"has_cycle": True, "edge": None}- Run
Trace Example 1 and Example 4 end to end
Let's verify both cyclic examples step by step:
Example 1: n = 4, edges = [0: [0, 2], 1: [2, 3], 2: [3, 2], 3: [0, 1]] 1. Full Kahn run: - Pod 0 has indegree 0 -> built! Enqueues pod 1 (indegree 0 -> built) and drops pod 2's indegree to 1. - Queue is now empty; pods 2 and 3 remain stuck: is_stuck = [False, False, True, True]. 2. Extract cycle among stuck pods {2, 3}: - incoming_edge_idx[3] = 1 (2 -> 3), incoming_edge_idx[2] = 2 (3 -> 2); note edge 0 (0 -> 2) is ignored because pod 0 is NOT stuck! - Backward walk from pod 2: pod 2 --(edge 2)--> pod 3 --(edge 1)--> pod 2 (repeat!). - Extracted cycle indices: [2, 1] -> sorted candidates: [1, 2]. 3. Test candidate index 1 ([2, 3]): - Remaining edges: [0, 2], [3, 2], [0, 1]. Build order 0, 3, 1, 2 succeeds -> no stuck pods! - Output: {"has_cycle": True, "edge": [2, 3]}. Example 4: n = 5, edges = [0: [1, 2], 1: [2, 3], 2: [3, 1], 3: [3, 4], 4: [0, 1]] 1. Full Kahn run: pod 0 builds; pods 1..4 remain stuck -> is_stuck = [False, True, True, True, True]. 2. Backward walk from pod 1: pod 1 --(2)--> pod 3 --(1)--> pod 2 --(0)--> pod 1. - Sorted candidates: [0, 1, 2] (downstream edge 3 and upstream edge 4 are never tested). 3. Test candidate index 0 ([1, 2]): - Remaining edges: 2 -> 3 -> 1, 3 -> 4, and 0 -> 1. Build order 0, 2, 3, 1, 4 succeeds! - Output: {"has_cycle": True, "edge": [1, 2]}.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def find_stuck_pods(n: int, edges: List[List[int]], skip_edge_idx: int) -> List[bool]: """Run Kahn's topological sort ignoring `edges[skip_edge_idx]` (-1 keeps all edges). Returns is_stuck[pod] == True for every pod that can never be built. """ # indegree[pod]: number of unbuilt prerequisite edges currently pointing into `pod` indegree = [0] * n # out_neighbors[u]: list of pods `v` that directly depend on `u` (edges u -> v) out_neighbors = [[] for _ in range(n)] for edge_idx in range(len(edges)): if edge_idx == skip_edge_idx: continue u, v = edges[edge_idx] out_neighbors[u].append(v) indegree[v] += 1 # ready_queue: pods with 0 remaining prerequisites, ready to build immediately ready_queue = deque() for pod in range(n): if indegree[pod] == 0: ready_queue.append(pod) # is_stuck[pod]: starts True and flips to False as soon as `pod` gets built is_stuck = [True] * n while ready_queue: built_pod = ready_queue.popleft() is_stuck[built_pod] = False for dependent_pod in out_neighbors[built_pod]: indegree[dependent_pod] -= 1 if indegree[dependent_pod] == 0: ready_queue.append(dependent_pod) return is_stuck def extract_one_cycle(n: int, edges: List[List[int]], is_stuck: List[bool]) -> List[int]: """Return the edge indices of one simple directed cycle by walking backward among stuck pods.""" # Every stuck pod `v` still had indegree > 0 after all buildable pods were removed, # so `v` is guaranteed to have at least one incoming edge `u -> v` from another stuck pod `u`. # incoming_edge_idx[v]: index in `edges` of one stuck -> stuck edge entering `v`, or -1 incoming_edge_idx = [-1] * n for edge_idx in range(len(edges)): u, v = edges[edge_idx] if is_stuck[u] and is_stuck[v] and incoming_edge_idx[v] == -1: incoming_edge_idx[v] = edge_idx current_pod = is_stuck.index(True) # visit_step[pod]: index in `walk_edges` when `pod` was first visited, or -1 if unvisited visit_step = [-1] * n # walk_edges: edge indices followed backward (v <- u) until a pod repeats walk_edges = [] while visit_step[current_pod] == -1: visit_step[current_pod] = len(walk_edges) edge_idx = incoming_edge_idx[current_pod] prev_pod = edges[edge_idx][0] walk_edges.append(edge_idx) current_pod = prev_pod # Slicing from `visit_step[current_pod]` drops any lead-in tail walked before entering the cycle. cycle_start = visit_step[current_pod] return walk_edges[cycle_start:] def detect_cycle_and_break(n: int, edges: List[List[int]]) -> Dict[str, object]: # Phase 1: check whether the full graph (skip_edge_idx = -1) has any unbuildable pods. is_stuck = find_stuck_pods(n, edges, skip_edge_idx=-1) if not any(is_stuck): return {"has_cycle": False, "edge": None} # Phase 2: any single edge whose removal breaks ALL cycles must belong to EVERY cycle, # so it must appear among the edges of the one simple cycle we extract here. # Sorting indices tests candidates in original input order for deterministic tie-breaking. candidate_edge_indices = sorted(extract_one_cycle(n, edges, is_stuck)) for edge_idx in candidate_edge_indices: stuck_after_removal = find_stuck_pods(n, edges, skip_edge_idx=edge_idx) if not any(stuck_after_removal): u, v = edges[edge_idx] return {"has_cycle": True, "edge": [u, v]} # Fallback if the graph violates the one-edge-fix assumption (e.g., two disjoint cycles). return {"has_cycle": True, "edge": None}✅ Submit now — all tests should pass.
Intuition & how it works
Imagine installing software pods where each rule u -> v says "pod u must finish installing before pod v can start." A natural way to install everything is to start every pod with zero prerequisites, cross those finished pods off everyone else's prerequisite lists, and repeat. If every pod eventually installs, there is no circular deadlock. If the installer stalls with pods still waiting, a circular dependency is blocking them — and if snipping one single dependency rule can untangle every loop in the system, that rule must sit inside every loop, so we only need to trace one loop and test the edges along it!
Two naive approaches fail in opposite ways. Trying to delete each of the m edges one at a time and re-checking the whole graph takes O(m * (n + m)) time, which degrades to O(n^3) when a dense graph has m near n^2 edges. Conversely, finding a single loop and blindly returning whichever loop edge you stumbled onto first is wrong whenever two loops overlap: deleting an edge that belongs to Loop A but not Loop B leaves Loop B intact!
Instead, we model the pods as a directed graph (a network of nodes connected by one-way arrows u -> v) and check whether it is a DAG (directed acyclic graph, a directed graph containing zero cycles, where a cycle is a non-empty directed path that starts and ends at the same node). First, we run Kahn's algorithm (an iterative topological-sort procedure that repeatedly removes nodes whose in-degree — the count of remaining incoming prerequisites — is 0). If no pod remains stuck, has_cycle is False. Otherwise, every stuck pod still has at least one incoming edge from another stuck pod, so walking backward from any stuck pod is guaranteed to repeat a pod within n steps, handing us one simple cycle (a cycle of at most n edges with no repeated nodes). Because an edge that breaks all cycles must belong to this cycle too, we sort its edge indices and re-run Kahn's algorithm skipping one candidate at a time until no pod is stuck.
Let's trace a 3-pod graph with two overlapping cycles: edges = [[1, 2], [2, 0], [0, 1], [1, 0]] (indices 0..3):
- Kahn's check: Initial in-degrees are
pod 0: 2,pod 1: 1,pod 2: 1. Nobody has in-degree0, sois_stuck = [True, True, True](has_cycle = True). - Backward walk: Suppose
incoming_edge_idxpicks0 -> 1(idx2),1 -> 2(idx0), and2 -> 0(idx1). Walking backward from0visits0 <- 2 <- 1 <- 0, extracting the simple cycle[1, 0, 2], which sorts to candidate indices[0, 1, 2]. - Test candidates: Skipping idx
0(1 -> 2) still leaves cycle0 -> 1 -> 0stuck; skipping idx1(2 -> 0) still leaves0 -> 1 -> 0stuck; skipping idx2(0 -> 1) lets pods build in order1, 2, 0! We return{"has_cycle": True, "edge": [0, 1]}.
Complexity
Let n be the number of pods and m be the number of dependency edges, and let L be the number of edges on the extracted simple cycle (1 <= L <= n).
- Time:
O(n + m)when the graph is acyclic, andO(L * (n + m))(at mostO(n * (n + m))) when a cycle exists. Buildingout_neighborsand running Kahn's queue touches each of thenpods andmedges once (O(n + m)), walking backward to extract one simple cycle visits at mostn + 1pods (O(n + m)), sortingL <= nindices takesO(L log L), and testing each of theLcycle edges runs Kahn's algorithm once (O(n + m)per candidate, vsmruns for brute force). - Space:
O(n + m). The adjacency listout_neighborsstores at mostmneighbor entries, and the per-pod arrays (indegree,is_stuck,incoming_edge_idx,visit_step,walk_edges, andready_queue) each hold at mostnentries.
Edge cases
- Already acyclic graph (including diamonds like
0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3): two separate paths to pod3are not a cycle; Kahn's algorithm builds every pod and returns{"has_cycle": False, "edge": None}. - Single pod with no edges (
n = 1, edges = []): pod0starts with in-degree0and builds immediately. - Self-loop (
[v, v]):vnever reaches in-degree0, and the backward walk returns tovin 1 step, identifying[v, v]as the 1-edge cycle (Example 3). - Duplicate (parallel) edges (
[[0, 1], [1, 0], [0, 1]]): skipping index0leaves index2([0, 1]) in the graph so the cycle survives; working with edge indices rather than(u, v)values rightly rejects[0, 1]and picks[1, 0]. - Pods downstream or upstream of a cycle: upstream pods (
0 -> 2feeding into2 <-> 3in Example 1) are built and cleared by Kahn's algorithm; downstream pods (3 -> 4hanging off1 -> 2 -> 3 -> 1in Example 4) stay stuck, and slicingwalk_edges[visit_step[current_pod]:]trims off any downstream tail walked before entering the cycle. - Disconnected components: Kahn's algorithm processes all components in a single pass, finding a cycle even if earlier components are acyclic.
Common mistakes
- Returning the first back-edge found by DFS without re-checking: breaks only the cycle currently being explored and fails whenever a chord or second cycle bypasses that edge.
- Walking forward instead of backward from a stuck pod: stuck pods downstream of a cycle (like pod
4in Example 4) can have zero outgoing edges, trapping a forward walk at a dead end. Walking backward among stuck pods is guaranteed never to dead-end. - Treating every stuck pod's edges as cycle edges: downstream non-cycle edges also connect two stuck pods; always extract a closed cycle or verify candidate removal.
- Skipping
(u, v)by value instead of by index: accidentally deletes all copies of a duplicated edge at once, making a non-working single-edge removal look like it fixed the graph. - Using recursive DFS without raising or avoiding recursion depth: chains of
2,000+pods hit Python's defaultRecursionErrorlimit (1000), whereas iterative Kahn's algorithm handles any depth safely.
Alternative approaches
- Iterative three-color DFS: mark each node
0(unvisited),1(currently on the active path), or2(completely explored without cycles). Seeing an edge to a state-1node immediately reveals one simple cycle on the active path stack, after which you still verify each edge of that cycle. - Linear-time
O(n + m)all-cycle edge finding: in advanced graph theory, splitting each edge into a vertex reduces "edges belonging to every cycle" to finding all feedback vertices inO(n + m)time (Garey & Tarjan, 1978, or computing furthest-reaching bypass chords around one cycle). That machinery is far too complex for a 45-minute coding interview unlessnandLare both10^5.
Follow-up questions
- How would you modify the algorithm to return all single edges whose individual removal makes the graph acyclic? The exact same key insight still holds: every such edge must lie on the single simple cycle
Creturned byextract_one_cycle. Instead of returning on the firstedge_idxinCthat leaves zero stuck pods, collect alledge_idxinCthat passnot any(find_stuck_pods(n, edges, edge_idx))— stillO(L * (n + m))total time. - What if no single edge removal breaks every cycle and you want to delete the minimum number of edges overall? Finding the smallest set of directed edges whose removal leaves a DAG is called the minimum feedback arc set problem (a classic NP-hard optimization problem, meaning no fast exact polynomial-time algorithm is known for arbitrary large graphs). For small graphs you can use branch-and-bound or integer linear programming; in real dependency managers, cycles are almost always authoring mistakes, so reporting the cycle path from
extract_one_cycleto the developer is much safer than silently dropping multiple dependencies. - After removing the chosen cycle-breaking edge, how do you produce a valid pod build order? Run Kahn's algorithm one more time with
skip_edge_idxset to the chosen edge and append eachbuilt_podpopped fromready_queueto aninstall_orderlist. Because a pod entersready_queueonly after all of its remaining prerequisites have been popped,install_orderis a valid topological build sequence of lengthn.
Follow-up questions
- How would you modify the algorithm to return all single edges whose individual removal makes the graph acyclic?
- What if no single edge removal breaks every cycle and you want to delete the minimum number of edges overall?
- After removing the chosen cycle-breaking edge, how do you produce a valid pod build order?
Similar questions
- Versioned Key-Value Store Queries
- Best-Fit GPU Pod Placement and Node Drain Check
- Balance Whole Lines Across Chunked Text
- GPU-Aware Cluster Manager and Pod Scheduler
- Tracing Linux CPU Bottlenecks from Host to Code
- Isolating Low Network Bandwidth Across Hosts and Containers
More Together AI interview questions
- Best-Fit GPU Pod Placement and Node Drain Check Medium
- GPU-Aware Cluster Manager and Pod Scheduler Hard
- Tracing Linux CPU Bottlenecks from Host to Code Easy Pro
- Isolating Low Network Bandwidth Across Hosts and Containers Easy Pro
- Pinpointing Storage Bottlenecks and Competing Disk Workloads Easy Pro
- Versioned Key-Value Store Queries Medium Pro
- Triage and Prevention of Logging-Induced Host Overload Easy Pro
- Balance Whole Lines Across Chunked Text Easy Pro