Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Detect Cycles in Routing Graph

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Detect Cycles in Routing Graph. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Visa payment routing paths form a directed graph. Each node represents a routing participant or processing stage, and an edge u -> v means a payment may be forwarded from u to v. Implement a function that determines whether any routing path contains a directed cycle.

A cycle exists if a path can start at a node and follow directed edges back to that same node. The graph may be disconnected, may contain self-loops, and may reference a node that has no outgoing edges.

Formal Specification

Implement detect_cycle(graph), where graph is a dictionary mapping each node identifier to a list of directly reachable node identifiers. Node identifiers are strings. Return True if the graph contains at least one directed cycle; otherwise, return False.

The solution must handle graphs with up to 100,000 nodes and edges without relying on Python's recursive call stack.

Constraints

  • 1 <= number of distinct nodes <= 100,000
  • 0 <= number of directed edges <= 200,000
  • Each node identifier is a non-empty string
  • A node may appear as a neighbor without being a key in graph
  • Duplicate edges may appear
  • The graph can contain multiple disconnected components

Function Signature

def detect_cycle(graph):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output