Class Solution

  • All Implemented Interfaces:

    
    public final class Solution
    
                        

    2360 - Longest Cycle in a Graph\.

    Hard

    You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

    The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.

    Return the length of the longest cycle in the graph. If no cycle exists, return -1.

    A cycle is a path that starts and ends at the same node.

    Example 1:

    Input: edges = 3,3,4,2,3

    Output: 3

    Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.

    The length of this cycle is 3, so 3 is returned.

    Example 2:

    Input: edges = 2,-1,3,1

    Output: -1

    Explanation: There are no cycles in this graph.

    Constraints:

    • n == edges.length

    • <code>2 <= n <= 10<sup>5</sup></code>

    • -1 &lt;= edges[i] &lt; n

    • edges[i] != i

    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
    • Field Summary

      Fields 
      Modifier and Type Field Description
    • Constructor Summary

      Constructors 
      Constructor Description
      Solution()
    • Enum Constant Summary

      Enum Constants 
      Enum Constant Description
    • Method Summary

      Modifier and Type Method Description
      final Integer longestCycle(IntArray edges)
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait