VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-equal-sum-components-can-be-obtained-from-given-graph-by-removing-edges-from-a-cycle/

⇱ Check if equal sum components can be obtained from given Graph by removing edges from a Cycle - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if equal sum components can be obtained from given Graph by removing edges from a Cycle

Last Updated : 23 Jul, 2025

Given an undirected graph with N vertices and N edges that contain only one cycle, and an array arr[] of size N, where arr[i] denotes the value of the ith node, the task is to check if the cycle can be divided into two components such that the sum of all the node values in both the components is the same.

Examples:

Input: N = 10, arr[] = {4, 2, 3, 3, 1, 2, 6, 2, 2, 5}, edges[] = {{1, 2}, {1, 5}, {1, 3}, {2, 6}, {2, 7}, {2, 4}, {4, 8}, {4, 3}, {3, 9}, {9, 10} } 
 

👁 Image


Output: Yes
Explanation: By removing the edges 1-2 and 3-4, the sum of all the node values of both the generated components is equal to 15.

👁 Image

Input: N= 4, arr[] = {1, 2, 3, 3}, edges[] = {{1, 2}, {2, 3}, {3, 4}, {2, 4}} 
 

👁 Image


Output: No 
Explanation: No possible way exists to obtain two equal sum components by removing an edges from the cycle.

Approach: The idea to solve this problem is to first find the nodes which are part of the cycle. Then, add the value of each node that is not a part of the cycle to its nearest node in the cycle. The final step involves checking whether the cycle can be divided into two equal sum components. Below are the steps:

  • The first step is to find all the nodes which are a part of a cycle using detect cycle in an undirected graph using DFS.
  • Perform the DFS Traversal on the given graph and do the following:
    • Mark the current node as visited. For each unvisited node connected to the current node recursively perform the DFS Traversal for each node.
    • If the adjacent node of the current node is already visited and is not the same as the previous node of the current node then it means that the current node is part of the cycle. Backtrack till this specific adjacent node is reached to find all nodes that are part of the cycle and store them in a vector inCycle[].
  • Find the sum of values for each node in the inCycle[] and add this sum to the current inCycle[] node value.
  • Find the total sum of values of all the nodes present in inCycle[] and store it in a variable totalSum. If the value of totalSum is odd then print "No" because the cycle with an odd sum cannot be divided into two equal sum components.
  • Otherwise, check if the value of totalSum/2 is present in inCycle[] then print "Yes" Else print "No".

Below is the implementation of the above approach:


Output: 
Yes

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment