Search⌘ K
AI Features

Solution: Longest Cycle in a Graph

Explore how to identify the longest cycle in a directed graph with nodes having at most one outgoing edge. Learn to traverse the graph efficiently, detect cycles using step counters, and calculate cycle lengths. This lesson helps you write an optimized solution with O(n) time complexity and enhances your understanding of graph pattern algorithms relevant to 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]. ...