Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Longest Cycle in a Graph LeetCode Solution

Problem – Longest Cycle in a Graph LeetCode Solution

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.


  • n == edges.length
  • 2 <= n <= 105
  • -1 <= edges[i] < n
  • edges[i] != i

Longest Cycle in a Graph LeetCode Solution in C++

   int maxLength = -1;

    void getcycle(vector<int> &edges,int si,vector<bool>& visit,int size,vector<int>& store){
        if(si == -1)return ;
            int count = -1;
            for(int i =0;i<store.size();i++){
                    count = i;
                } }
            maxLength = max(maxLength,size-count);  // size-count gives the proper size of cycle
            return ;
        visit[si] = true;
        return ;
    int longestCycle(vector<int>& edges) {
        vector<bool> visit(edges.size(),0);
        for(int i =0;i<edges.size();i++){
            vector<int> store;
        return maxLength;

Longest Cycle in a Graph LeetCode Solution in Java

public int longestCycle(int[] edges) {
    int res = -1;
    boolean[] vis = new boolean[edges.length]; // global visisted
    for(int i=0; i<edges.length; i++){
        if(vis[i]) continue;
        int dist = 0, idx = i;
        HashMap<Integer, Integer> x = new HashMap<>();  // local visited
                res = Math.max(res, dist-x.get(idx));
            if(vis[idx]) break;
            vis[idx] = true;
            x.put(idx, dist++);
            idx = edges[idx];
    return res;

Longest Cycle in a Graph LeetCode Solution in Python

def longestCycle(self, edges: List[int]) -> int:
    n = len(edges)
    self.max_length = float('-inf')
    seen = [False] * n
    visiting = {}
    stack = []
    def dfs(node):
        if not seen[node]:
            if node in visiting:
                self.max_length = max(self.max_length, len(stack) - visiting[node])
            elif edges[node] != -1: 
                visiting[node] = len(stack) 
            seen[node] = True
    for i in range(n):            
    return self.max_length if self.max_length > 0 else -1    
Longest Cycle in a Graph LeetCode Solution Review:

In our experience, we suggest you solve this Longest Cycle in a Graph LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Longest Cycle in a Graph LeetCode Solution

Find on LeetCode


I hope this Longest Cycle in a Graph LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *