Tap here to switch tabs
Problem
Ask
Submissions

Problem: Longest Cycle in a Graph

hard
40 min
Explore how to detect and find the longest cycle in a directed graph where each node has at most one outgoing edge. This lesson helps you understand cycle definitions, apply constraints, and implement an efficient solution in coding interviews.

Statement

You are given a directed graph with n nodes, labeled from 0 to n - 1. Each node in the graph has at most one outgoing edge.

The graph is described using a 0-indexed integer array edges of length n, where:

  • edges[i] represents a directed edge from node i to node edges[i].

  • If node i has no outgoing edge, then edges[i] == -1.

Your task is to find the longest cycle length in the graph. If no cycle exists, return -1.

Note: A cycle is defined as a path that starts and ends at the same node, following the direction of the edges.

Constraints:

  • n ==== edges.length

  • 22 \leq n 105 \leq 10^{5}

  • 1-1 \leq edges[i] \leq n

  • edges[i] \neqi

Tap here to switch tabs
Problem
Ask
Submissions

Problem: Longest Cycle in a Graph

hard
40 min
Explore how to detect and find the longest cycle in a directed graph where each node has at most one outgoing edge. This lesson helps you understand cycle definitions, apply constraints, and implement an efficient solution in coding interviews.

Statement

You are given a directed graph with n nodes, labeled from 0 to n - 1. Each node in the graph has at most one outgoing edge.

The graph is described using a 0-indexed integer array edges of length n, where:

  • edges[i] represents a directed edge from node i to node edges[i].

  • If node i has no outgoing edge, then edges[i] == -1.

Your task is to find the longest cycle length in the graph. If no cycle exists, return -1.

Note: A cycle is defined as a path that starts and ends at the same node, following the direction of the edges.

Constraints:

  • n ==== edges.length

  • 22 \leq n 105 \leq 10^{5}

  • 1-1 \leq edges[i] \leq n

  • edges[i] \neqi