Negative weight cycle | Practice | GeeksforGeeks

Given a weighted directed graph with n nodes and m edges. Nodes are labeled from 0 to n-1, the task is to check if it contains a negative weight cycle or not.
Note: edges[i] is defined as u, v and weight.
 
Example 1:
Input: n = 3, edges = {{0,1,-1},{1,2,-2},
{2,0,-3}}
Output: 1
Explanation: The graph contains negative weight
cycle as 0->1->2->0 with weight -1,-2,-3.

Example 2:
Input: n = 3, edges = {{0,1,-1},{1,2,-2},
{2,0,3}}
Output: 0
Explanation: The graph does not contain any
negative weight cycle.

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function isNegativeWeightCycle() which takes n and edges as input paramater and returns 1 if graph contains negative weight cycle otherwise returns 0.
 
Expected Time Complexity: O(n*m)
Expected Space Compelxity: O(n)
 
Constraints:
1 <= n <= 100
1 <= m <= n*(n-1), where m is the total number of Edges in the directed graph.
0
ashishnair7322 days ago
BEST PYTHON SOLUTION AVAILABLE:
 
def isNegativeWeightCycle(self, n, edges): #Code here maxVal = 99999 dist = [maxVal] * n dist[0] = 0  for count in range(n):     for j in range(len(edges)):         src = edges[j][0]         dest = edges[j][1]         weigh = edges[j][2]                  if dist[src] != maxVal and dist[src] + weigh < dist[dest]:             dist[dest] = dist[src]+weigh                    for j in range(len(edges)):           src = edges[j][0]     dest = edges[j][1]     weigh = edges[j][2]              if dist[src] != maxVal and dist[src] + weigh < dist[dest]:         return 1              return 0
0
vishaldasani2 weeks ago
why using INT_MAX in distance array giving wrong answer.
0
asissrmakumar6662 weeks ago
JAVA | Time: 0.59/10.22 | Bellman Ford Algorithm

class Solution
{
    public int isNegativeWeightCycle(int n, int[][] edges)
    {
        int dist[]=new int[n];
        Arrays.fill(dist,10000000);
        dist[0]=0;
        for(int i=1;i<n;i++){
            for(int []arr:edges){
                if(dist[arr[0]]+arr[2]<dist[arr[1]]){
                    dist[arr[1]]=dist[arr[0]]+arr[2];
                }
            }
        }
        for(int []arr:edges){
            if(dist[arr[0]]+arr[2]<dist[arr[1]]){
                    return 1;
                }
        }
        return 0;
    }
}
+1
avinashdhn19042 weeks ago
// using bellman ford algorithm
/* if after n-1 iterations still there is some relaxation happens in the nth iteration then that graph will definitely have negative weight cycle*/

	int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    vector<int>dist(n,1000000007);
	    dist[0]=0;
	    for(int i=0;i<n;i++){
	        int flag=0;
	        for(auto e:edges){
	            int u=e[0];
	            int v=e[1],w=e[2];
	            if(dist[u]+w<dist[v]){dist[v]=dist[u]+w;flag=1;}
	        }
	        if(i==n-1&&flag)return 1;
	    }
	    return 0;
	}
+1
pratikbhankhodiya2 weeks ago
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    vector<int> dis(n,1e6);
	    dis[0]=0;
	    for(int i=1;i<n;i++){
	        for(auto &p:edges){
	            if(dis[p[0]]+p[2]<dis[p[1]]){
	                dis[p[1]]=p[2]+dis[p[0]];
	            }
	        }
	    }
	    for(auto &p:edges){
	        if(dis[p[0]]+p[2]<dis[p[1]]) return 1;
	    }
	    return 0;
	}
+2
jacksllager2 weeks ago
C++ solution - Graph (ballmon ford algo)
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    vector<int>dist(n, INT_MAX);
	    dist[0] = 0;
	    for(int i = 1;i<=n-1;i++) for(auto edge : edges) if(dist[edge[0]] != INT_MAX && dist[edge[0]] + edge[2] < dist[edge[1]]) dist[edge[1]] = dist[edge[0]] + edge[2];
	    for(auto edge : edges) if(dist[edge[0]] != INT_MAX && dist[edge[0]] + edge[2] < dist[edge[1]]) return 1;
	    return 0;
	    }
+1
akshitasinghal44442 weeks ago
C++ | Bellman Ford
Time - O ( n * n )
Space - O ( n )
		vector<int> dis(n,INT_MAX);
	    dis[0]=0;
	    int i,j;
	    
	    for(i=0;i<n-1;i++)
	    {
	        for(auto e:edges)
	        {
	            int u=e[0],v=e[1],d=e[2];
	            
	            if(dis[u]!=INT_MAX && dis[u]+d<dis[v])
	                dis[v]=dis[u]+d;
	        }
	    }
	    
	    for(auto e:edges)
	    {
	        int u=e[0],v=e[1],d=e[2];
	        if(dis[u]!=INT_MAX && dis[u]+d<dis[v])
	        return 1;
	    }
	    
	    return 0;
0
disaster2 weeks ago
C++ - BFS
class Solution{	
	public:
    	void makeGraph(vector<vector<int>>& edges, vector<vector<int>> adj[]){
        	for(auto vec: edges){
            	adj[vec[0]].push_back({vec[1], vec[2]});
        	}
    	}
    	int bfs(int nd, int n, vector<vector<int>> adj[]){
        	queue<pair<int,int>> q;
	    	q.push({nd, 0});
	    	vector<bool> vis(n, false);
	    	while(!q.empty()){
	        	int node = q.front().first, dist = q.front().second; q.pop();
	        	vis[node] = true;
	        	for(auto vec: adj[node]){
	            	int nodes = vec[0], d = vec[1];
	            	if(!vis[nodes]){
	                	q.push({nodes, dist+d});
	            	}
	            	else{
	                	if(dist+d < 0)  return 1;
	            	}
	        	}
	    	}
	    	return 0;
    	}
		int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    	// Code here
	    	vector<vector<int>> adj[n];
	    	makeGraph(edges, adj);
	    	for(int i=0;i<n;i++){
	        	if(bfs(i, n, adj) == 1) return 1;
	    	}
	    	return 0;
		}
};
+1
pulavartivinay2 weeks ago
C++ | Graphs | Bellman Ford Algorithm
Time Complexity: O(n*m) | Space Complexity: O(n) | Execution Time: 0.2/2.8
 
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    // Code here
        vector<int> store(n,INT_MAX);
        store[0] = 0;
        for(int v=0;v<(n-1);v++)
        {
            for(int i=0;i<edges.size();i++)
            {
                int u = edges[i][0];
                int v = edges[i][1];
                int w = edges[i][2];
                if(store[u] != INT_MAX && store[v] > store[u] + w) store[v] = store[u] + w;
            }
        }
        
        //detection for negative weight cycle 
        for(int i=0;i<edges.size();i++)
        {
            int u = edges[i][0];
            int v = edges[i][1];
            int w = edges[i][2];
            if(store[u] != INT_MAX && store[v] > store[u] + w) return 1;
        }
	    return 0;
	}
0
rohith v2 weeks ago
My Java Solution using Bellmanford algorithm.
 
https://youtu.be/g0SjKmJavaI
 
class Solution
{
    public int isNegativeWeightCycle(int n, int[][] edges)
    {
        //code here
        if (edges == null || n == 0) {
            return 0;
        }
        int [] distance = new int [n];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[0] = 0;
        // n - 1 number of relaxation steps
        for (int i = 1; i <= n - 1; i++) {
            for (int [] edge : edges) {
                int source = edge[0];
                int destination = edge[1];
                int weight = edge[2];
                // condition
                if (distance[source] != Integer.MAX_VALUE && distance[source] + 
                weight < distance[destination]) {
                    distance[destination] = distance[source] + weight;
                }
            }
        }
        // relaxation step once more to make sure about the negative cycle
        for (int [] edge : edges) {
            int source = edge[0];
            int destination = edge[1];
            int weight = edge[2];
            if (distance[source] != Integer.MAX_VALUE && distance[source] + 
            weight < distance[destination]) {
                // there is a negative cycle as distance will get updated
                return 1;
            }
        }
        return 0;
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.