Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Graph DFS Problem Solving

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

Your question is Graph DFS Problem Solving. 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

Gro Intelligence represents data lineage as a directed graph. An edge [u, v] means that lineage node u directly depends on node v. A cyclic component indicates mutually dependent calculations that cannot be resolved in a valid dependency order.

Given n nodes labeled 0 through n - 1 and a list of directed edges, return every cyclic strongly connected component. A component is cyclic if it contains at least two nodes, or if it contains one node with a self-loop. Exclude nodes that are not part of a cycle.

Return the components as a list of lists. Sort node IDs within each component in ascending order, and sort the components by their smallest node ID.

Formal Specification

Implement find_cyclic_components(n, edges).

  • Input: integer n and list edges, where each edge is a two-element list [u, v].
  • Output: a list of sorted integer lists, containing exactly the cyclic strongly connected components.
  • The graph may be disconnected and may contain duplicate edges.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= u, v < n for every edge [u, v]
  • Duplicate edges may occur
  • The graph may be disconnected
  • A self-loop makes a single-node component cyclic

Function Signature

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