Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Cycle Detection in Directed Graph

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

Your question is Cycle Detection in Directed 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

Altruist can represent financial transaction flows as a directed graph, where each node is an account or processing step and an edge A -> B means value can move from A to B. Implement a function that determines whether the graph contains a directed cycle.

A cycle exists when following transaction edges can return to a previously visited node on the current traversal path. The graph may be disconnected.

Formal Specification

Implement detect_transaction_cycle(graph), where graph is a dictionary mapping each node to a list of directly reachable nodes. Nodes are strings, and every neighbor is also a string. Return True if any directed cycle exists, otherwise return False.

Constraints

  • 1 <= number of nodes <= 10^5
  • 0 <= number of edges <= 2 * 10^5
  • Node identifiers are non-empty strings
  • The graph may contain disconnected components
  • Neighbor nodes may be absent as keys and have no outgoing edges

Function Signature

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