Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
XOR Linked List - Find Nth Node from the end
Next article icon

Find the balanced node in a Linked List

Last Updated : 17 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list, the task is to find the balanced node in a linked list. A balanced node is a node where the sum of all the nodes on its left is equal to the sum of all the node on its right, if no such node is found then print -1.

Examples:  

Input: 1 -> 2 -> 7 -> 10 -> 1 -> 6 -> 3 -> NULL 
Output: 10 
Sum of nodes on the left of 10 is 1 + 2 + 7 = 10 
And, to the right of 10 is 1 + 6 + 3 = 10

Input: 1 -> 5 -> 5 -> 10 -> -3 -> NULL 
Output: -1 

Approach:  

  • First, find the total sum of the all node values.
  • Now, traverse the linked list one by one and while traversing keep track of all the previous nodes value sum and find the sum of the remaining node by subtracting current node value and the sum of the previous nodes value from the total sum.
  • Compare both the sums, if they are equal then current node is the required node else print -1.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a node of linked list
class Node {
public:
    int data;
    Node* next;
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
  
// Push the new node to front of
// the linked list
Node* push(Node* head, int data)
{
      
    // Return new node as head if
    // head is empty
    if (head == NULL)
    {
        return new Node(data);
    }
    Node* temp = new Node(data);
    temp->next = head;
    head = temp;
    return head;
}
  
// Function to find the balanced node
int findBalancedNode(Node* head)
{
    int tsum = 0;
    Node* curr_node = head;
      
    // Traverse through all node
    // to find the total sum
    while (curr_node != NULL)
    {
        tsum += curr_node->data;
        curr_node = curr_node->next;
    }
  
    // Set current_sum and remaining
    // sum to zero
    int current_sum = 0;
    int remaining_sum = 0;
    curr_node = head;
  
    // Traversing the list to
    // check balanced node
    while (curr_node != NULL)
    {
        remaining_sum = tsum - (current_sum +
                               curr_node->data);
  
        // If sum of the nodes on the left and
        // the current node is equal to the sum
        // of the nodes on the right
        if (current_sum == remaining_sum)
        {
            return curr_node->data;
        }
        current_sum += curr_node->data;
        curr_node = curr_node->next;
    }
    return -1;
}
 
// Driver code
int main()
{
    Node* head = NULL;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
    cout << findBalancedNode(head);
    return 0;
}
 
// This code is contributed by divyehrabadiya07
 
 

Java




// Java implementation of the approach
class GFG{
     
// Structure of a node of linked list
static class Node
{
    int data;
    Node next;
     
    Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}
 
// Push the new node to front of
// the linked list
static Node push(Node head, int data)
{
     
    // Return new node as head if
    // head is empty
    if (head == null)
    {
        return new Node(data);
    }
    Node temp = new Node(data);
    temp.next = head;
    head = temp;
    return head;
}
 
// Function to find the balanced node
static int findBalancedNode(Node head)
{
    int tsum = 0;
    Node curr_node = head;
     
    // Traverse through all node
    // to find the total sum
    while (curr_node != null)
    {
        tsum += curr_node.data;
        curr_node = curr_node.next;
    }
 
    // Set current_sum and remaining
    // sum to zero
    int current_sum = 0;
    int remaining_sum = 0;
    curr_node = head;
 
    // Traversing the list to
    // check balanced node
    while (curr_node != null)
    {
        remaining_sum = tsum - (current_sum +
                               curr_node.data);
 
        // If sum of the nodes on the left and
        // the current node is equal to the sum
        // of the nodes on the right
        if (current_sum == remaining_sum)
        {
            return curr_node.data;
        }
        current_sum += curr_node.data;
        curr_node = curr_node.next;
    }
    return -1;
}
 
// Driver code
public static void main(String []args)
{
    Node head = null;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
 
    System.out.println(findBalancedNode(head));
}
}
 
// This code is contributed by rutvik_56
 
 

Python3




# Python3 implementation of the approach
import sys
import math
 
# Structure of a node of linked list
class Node:
    def __init__(self, data):
        self.next = None
        self.data = data
 
# Push the new node to front of the linked list
def push(head, data):
 
    # Return new node as head if head is empty
    if not head:
        return Node(data)
    temp = Node(data)
    temp.next = head
    head = temp
    return head
 
# Function to find the balanced node
def findBalancedNode(head):
    tsum = 0
    curr_node = head
     
    # Traverse through all node
    # to find the total sum
    while curr_node:
        tsum+= curr_node.data
        curr_node = curr_node.next
     
    # Set current_sum and remaining sum to zero
    current_sum, remaining_sum = 0, 0
    curr_node = head
 
    # Traversing the list to check balanced node
    while(curr_node):
        remaining_sum = tsum-(current_sum + curr_node.data)
 
        # If sum of the nodes on the left and the current node
        # is equal to the sum of the nodes on the right
        if current_sum == remaining_sum:
            return curr_node.data
        current_sum+= curr_node.data
        curr_node = curr_node.next
     
    return -1
 
# Driver code
if __name__=='__main__':
    head = None
    head = push(head, 3)
    head = push(head, 6)
    head = push(head, 1)
    head = push(head, 10)
    head = push(head, 7)
    head = push(head, 2)
    head = push(head, 1)
 
    print(findBalancedNode(head))
 
 

C#




// C# implementation of the approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
 
  // Structure of a node of linked list
  class Node
  {
    public int data;
    public Node next;
 
    public Node(int data)
    {
      this.data = data;
      this.next = null;
    }
  }
 
  // Push the new node to front of
  // the linked list
  static Node push(Node head, int data)
  {
 
    // Return new node as head if
    // head is empty
    if (head == null)
    {
      return new Node(data);
    }
    Node temp = new Node(data);
    temp.next = head;
    head = temp;
    return head;
  }
 
  // Function to find the balanced node
  static int findBalancedNode(Node head)
  {
    int tsum = 0;
    Node curr_node = head;
 
    // Traverse through all node
    // to find the total sum
    while (curr_node != null)
    {
      tsum += curr_node.data;
      curr_node = curr_node.next;
    }
 
    // Set current_sum and remaining
    // sum to zero
    int current_sum = 0;
    int remaining_sum = 0;
    curr_node = head;
 
    // Traversing the list to
    // check balanced node
    while (curr_node != null)
    {
      remaining_sum = tsum - (current_sum +
                              curr_node.data);
 
      // If sum of the nodes on the left and
      // the current node is equal to the sum
      // of the nodes on the right
      if (current_sum == remaining_sum)
      {
        return curr_node.data;
      }
      current_sum += curr_node.data;
      curr_node = curr_node.next;
    }
    return -1;
  }
 
  // Driver code
  public static void Main(string []args)
  {
    Node head = null;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
    Console.Write(findBalancedNode(head));
  }
}
 
// This code is contributed by pratham76
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
// Structure of a node of linked list
class Node {
        constructor(data) {
                this.data = data;
                this.next = null;
             }
        }
         
         
// Push the new node to front of
// the linked list
function push( head, data)
{
     
    // Return new node as head if
    // head is empty
    if (head == null)
    {
        return new Node(data);
    }
    var temp = new Node(data);
    temp.next = head;
    head = temp;
    return head;
}
 
// Function to find the balanced node
function findBalancedNode( head)
{
    let tsum = 0;
    let curr_node = head;
     
    // Traverse through all node
    // to find the total sum
    while (curr_node != null)
    {
        tsum += curr_node.data;
        curr_node = curr_node.next;
    }
 
    // Set current_sum and remaining
    // sum to zero
    let current_sum = 0;
    let remaining_sum = 0;
    curr_node = head;
 
    // Traversing the list to
    // check balanced node
    while (curr_node != null)
    {
        remaining_sum = tsum - (current_sum +
                            curr_node.data);
 
        // If sum of the nodes on the left and
        // the current node is equal to the sum
        // of the nodes on the right
        if (current_sum == remaining_sum)
        {
            return curr_node.data;
        }
        current_sum += curr_node.data;
        curr_node = curr_node.next;
    }
    return -1;
}
 
    // Driver Code
 
    var head = null;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
 
    document.write(findBalancedNode(head));
 
// This code is contributed by Jana_sayantan.
</script>
 
 

 
 

Output: 
10

 

Time Complexity: O(n)
Auxiliary Space: O(1) 
 



Next Article
XOR Linked List - Find Nth Node from the end

V

Vikash Kumar 37
Improve
Article Tags :
  • Advanced Data Structure
  • Data Structures
  • DSA
  • Linked List
  • Traversal
Practice Tags :
  • Advanced Data Structure
  • Data Structures
  • Linked List
  • Traversal

Similar Reads

  • Find extra node in the second Linked list
    Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
    7 min read
  • Program to find average of all nodes in a Linked List
    Given a singly linked list. The task is to find the average of all nodes of the given singly linked list. Examples: Input: 7->6->8->4->1 Output: 26 Average of nodes: (7 + 6 + 8 + 4 + 1 ) / 5 = 5.2 Input: 1->7->3->9->11->5 Output: 6 Iterative Solution: Initialise a pointer
    7 min read
  • Find sum of even and odd nodes in a linked list
    Given a linked list, the task is to find the sum of even and odd nodes in it separately. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 Output: Even Sum = 12 Odd Sum = 16 Input: 5 -> 7 -> 8 -> 10 -> 15 Output: Even Sum = 18 Odd Sum = 27 Approach: Traverse the whole li
    6 min read
  • XOR Linked List - Find Nth Node from the end
    Given a XOR linked list and an integer N, the task is to print the Nth node from the end of the given XOR linked list. Examples: Input: 4 –> 6 –> 7 –> 3, N = 1 Output: 3 Explanation: 1st node from the end is 3.Input: 5 –> 8 –> 9, N = 4 Output: Wrong Input Explanation: The given Xor Li
    15+ min read
  • Find first node of loop in a linked list
    Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1. Example: Input: Output: 3Ex
    14 min read
  • Sorted Linked List to Balanced BST
    Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List. Examples: Input: Linked List 1->2->3Output: A Balanced BST 2 / \ 1 3 Input: Linked List 1->2->3->4->5->6-
    15+ min read
  • Segregate even and odd nodes in a Linked List
    Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers. Examples: Input: 17->15->8->12->10->5->4->1->7->6->NULLOutp
    15+ min read
  • Find a peak element in Linked List
    Given a linked list of integers, the task is to find a peak element in the given linked list. An element is a peak, if it is greater than or equals to its neighbors. For boundary elements, consider only one neighbor. Examples: Input : List = {1 -> 6 -> 8 -> 4 -> 12} Output : 8Explanation
    8 min read
  • Find modular node in a linked list
    Given a singly linked list and a number k, find the last node whose n%k == 0, where n is the number of nodes in the list. Examples: Input : list = 1->2->3->4->5->6->7 k = 3 Output : 6 Input : list = 3->7->1->9->8 k = 2 Output : 9Recommended ProblemModular NodeSolve Prob
    5 min read
  • Find the common nodes in two singly linked list
    Given two linked list, the task is to find the number of common nodes in both singly linked list. Examples: Input: List A = 3 -> 4 -> 12 -> 10 -> 17, List B = 10 -> 4 -> 8 -> 575 -> 34 -> 12 Output: Number of common nodes in both list is = 3 Input: List A = 12 -> 4 -
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences