HardDepth-First SearchGraphTopological Sort

Longest Cycle in a Graph

LeetCode
1 approach, code in all languages

You are given a directed graph with n nodes labeled 0 to n - 1, described by an array edges of length n. Each node has at most one outgoing edge: edges[i] is the node that i points to, or -1 when node i has no outgoing edge.

Return the length of the longest cycle in the graph. If the graph contains no cycle at all, return -1.

Because every node has out-degree at most one, the paths form simple chains that either terminate at a -1 or loop back to a previously seen node.

Example 1

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

Output: 3

Following edges from node 2 gives 2 -> 4 -> 3 -> 2, a cycle of length 3, which is the longest one present.

Example 2

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

Output: -1

The chain 0 -> 2 -> 3 -> 1 ends at node 1, whose edge is -1. No path loops back, so there is no cycle.

Constraints

  • n == edges.length
  • 2 <= n <= 10^5
  • -1 <= edges[i] < n
  • edges[i] != i
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now