Longest Cycle in a Graph

HardGraphsdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A directed graph has n nodes labeled 0 to n - 1, and every node has **at most one** outgoing edge. It is given as an array edges: node i has an edge to edges[i], or no outgoing edge when edges[i] == -1. A cycle is a path that starts and ends at the same node without repeating any other node. Return the number of nodes in the **longest** cycle, or -1 if the graph has no cycle. No node points to itself. Aim for O(n) time.

Examples

Input: edges = [1,2,3,0,5,6,4,-1]
Output: 4
There are two cycles: 0 -> 1 -> 2 -> 3 -> 0 (length 4) and 4 -> 5 -> 6 -> 4 (length 3).
Input: edges = [-1,0,1]
Output: -1
Following edges from any node ends at node 0, which has no outgoing edge.

Constraints

  • n == edges.length
  • 2 <= n <= 10^5
  • -1 <= edges[i] < n
  • edges[i] != i

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems