VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-cycle-finding/

⇱ CSES Solutions – Cycle Finding - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions – Cycle Finding

Last Updated : 23 Jul, 2025

Given a directed graph with N nodes and M edges determine if there exists a negative cycle in the graph. If a negative cycle exists print "YES" and output any vertex sequence that forms the cycle; otherwise print "NO".

Examples:

Input:

4 5

1 2 1

2 4 1

3 1 1

4 1 -3

4 3 -2

Output:

YES

1 2 4 1

Approach:

To determine if there exists a negative cycle in the graph we can use the Shortest Path Faster Algorithm. We perform the relaxation on the all edges repeatedly for the n-1 iterations where n is the number of the nodes. If on the nth iteration we still find a relaxation and it indicates the presence of the negative cycle.

Step-by-step approach:

  • Use Shortest Path Faster Algorithm to find whether there is a negative weighted cycle in the graph or not.
  • While relaxing the nodes, maintain a parent array, say par[] which stores the parent of the node which we have relaxed.
  • If there is a negative weighted cycle in the graph, then print all the nodes in the cycle using the parent array.
  • If no cycle is present, simply print NO.

Below is the implementation of the algorithm:


Output
YES
2 4 1 2

Time Complexity: O(n * m)
Auxiliary Space: O(n)

Comment
Article Tags: