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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count of subarrays of size K with elements having even frequencies
Next article icon

Count subarrays having sum of elements at even and odd positions equal

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal.

Examples:

Input: arr[] = {1, 2, 3, 4, 1}
Output: 1
Explanation: 
{3, 4, 1} is the only subarray in which sum of elements at even position {3, 1} = sum of element at odd position {4}

Input: arr[] = {2, 4, 6, 4, 2}
Output: 2
Explanation: 
There are two subarrays {2, 4, 6, 4} and {4, 6, 4, 2}.

 

Approach: The idea is to generate all possible subarrays. For each subarray formed find the sum of the elements at even index and subtract the elements at odd index. If the sum is 0, count this subarray else check for the next subarray.

Below is the implementation of the above approach:

C++




// C program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to count subarrays in
// which sum of elements at even
// and odd positions are equal
void countSubarrays(int arr[], int n)
{
      
    // Initialize variables
    int count = 0;
  
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
        int sum = 0;
  
        for(int j = i; j < n; j++)
        {
              
            // Check if position is
            // even then add to sum
            // then add it to sum
            if ((j - i) % 2 == 0)
                sum += arr[j];
  
            // Else subtract it to sum
            else
                sum -= arr[j];
  
            // Increment the count
            // if the sum equals 0
            if (sum == 0)
                count++;
        }
    }
  
    // Print the count of subarrays
    cout << " " << count ;
}
  
// Driver Code
int main()
{
      
    // Given array arr[]
    int arr[] = { 2, 4, 6, 4, 2 };
  
    // Size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    countSubarrays(arr, n);
    return 0;
}
  
// This code is contributed by shivanisinghss2110
 
 

C




// C program for the above approach
#include <stdio.h>
  
// Function to count subarrays in
// which sum of elements at even
// and odd positions are equal
void countSubarrays(int arr[], int n)
{
      
    // Initialize variables
    int count = 0;
  
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
        int sum = 0;
  
        for(int j = i; j < n; j++)
        {
              
            // Check if position is
            // even then add to sum
            // then add it to sum
            if ((j - i) % 2 == 0)
                sum += arr[j];
  
            // Else subtract it to sum
            else
                sum -= arr[j];
  
            // Increment the count
            // if the sum equals 0
            if (sum == 0)
                count++;
        }
    }
  
    // Print the count of subarrays
    printf("%d", count);
}
  
// Driver Code
int main()
{
      
    // Given array arr[]
    int arr[] = { 2, 4, 6, 4, 2 };
  
    // Size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    countSubarrays(arr, n);
    return 0;
}
  
// This code is contributed by piyush3010
 
 

Java




// Java program for the above approach
import java.util.*;
class GFG {
  
    // Function to count subarrays in
    // which sum of elements at even
    // and odd positions are equal
    static void countSubarrays(int arr[],
                               int n)
    {
        // Initialize variables
        int count = 0;
  
        // Iterate over the array
        for (int i = 0; i < n; i++) {
            int sum = 0;
  
            for (int j = i; j < n; j++) {
  
                // Check if position is
                // even then add to sum
                // then add it to sum
                if ((j - i) % 2 == 0)
                    sum += arr[j];
  
                // else subtract it to sum
                else
                    sum -= arr[j];
  
                // Increment the count
                // if the sum equals 0
                if (sum == 0)
  
                    count++;
            }
        }
  
        // Print the count of subarrays
        System.out.println(count);
    }
  
    // Driver Code
    public static void
        main(String[] args)
    {
        // Given array arr[]
        int arr[] = { 2, 4, 6, 4, 2 };
  
        // Size of the array
        int n = arr.length;
  
        // Function call
        countSubarrays(arr, n);
    }
}
 
 

Python3




# Python3 program for the above approach
  
# Function to count subarrays in
# which sum of elements at even
# and odd positions are equal
def countSubarrays(arr, n):
  
    # Initialize variables
    count = 0
  
    # Iterate over the array
    for i in range(n):
        sum = 0
          
        for j in range(i, n):
  
            # Check if position is
            # even then add to sum
            # hen add it to sum
            if ((j - i) % 2 == 0):
                sum += arr[j]
  
            # else subtract it to sum
            else:
                sum -= arr[j]
  
            # Increment the count
            # if the sum equals 0
            if (sum == 0):
                count += 1
                  
    # Print the count of subarrays
    print(count)
  
# Driver Code
if __name__ == '__main__':
    
    # Given array arr[]
    arr = [ 2, 4, 6, 4, 2 ]
  
    # Size of the array
    n = len(arr)
  
    # Function call
    countSubarrays(arr, n)
  
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
using System;
  
class GFG{
  
// Function to count subarrays in
// which sum of elements at even
// and odd positions are equal
static void countSubarrays(int []arr, int n)
{
      
    // Initialize variables
    int count = 0;
  
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
        int sum = 0;
  
        for(int j = i; j < n; j++) 
        {
              
            // Check if position is
            // even then add to sum
            // then add it to sum
            if ((j - i) % 2 == 0)
                sum += arr[j];
  
            // else subtract it to sum
            else
                sum -= arr[j];
  
            // Increment the count
            // if the sum equals 0
            if (sum == 0)
                count++;
        }
    }
  
    // Print the count of subarrays
    Console.WriteLine(count);
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given array []arr
    int []arr = { 2, 4, 6, 4, 2 };
  
    // Size of the array
    int n = arr.Length;
  
    // Function call
    countSubarrays(arr, n);
}
}
  
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
  
// javascript program for the above approach
  
// Function to count subarrays in
// which sum of elements at even
// and odd positions are equal
function countSubarrays(arr, n)
{
      
    // Initialize variables
    var count = 0;
    var i,j;
    // Iterate over the array
    for(i = 0; i < n; i++)
    {
        var sum = 0;
  
        for(j = i; j < n; j++)
        {
              
            // Check if position is
            // even then add to sum
            // then add it to sum
            if ((j - i) % 2 == 0)
                sum += arr[j];
  
            // Else subtract it to sum
            else
                sum -= arr[j];
  
            // Increment the count
            // if the sum equals 0
            if (sum == 0)
                count++;
        }
    }
  
    // Print the count of subarrays
    document.write(count);
}
  
// Driver Code
      
    // Given array arr[]
    var arr = [2, 4, 6, 4, 2];
  
    // Size of the array
    var n = arr.length;
  
    // Function call
    countSubarrays(arr, n);
  
</script>
 
 
Output: 
2

 

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Count of subarrays of size K with elements having even frequencies
author
jrishabh99
Improve
Article Tags :
  • Analysis of Algorithms
  • Arrays
  • Competitive Programming
  • DSA
  • Greedy
  • Mathematical
  • subarray
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Count of odd and even parity elements in subarray using MO's algorithm
    Given an array arr consisting of N elements and Q queries represented by L and R denoting a range, the task is to print the count of odd and even parity elements in the subarray [L, R]. Examples: Input: arr[]=[5, 2, 3, 1, 4, 8, 10] Q=2 1 3 0 4 Output: 2 1 3 2 Explanation: In query 1, odd parity elem
    13 min read
  • Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K
    Given an array arr[] of size N and an integer K, the task is to split the given array into maximum possible subarrays having equal count of even and odd elements such that the cost to split the array does not exceed K. The cost to split an array into a subarray is the difference between the last and
    8 min read
  • Count subarrays with same even and odd elements
    Given an array of N integers, count number of even-odd subarrays. An even - odd subarray is a subarray that contains the same number of even as well as odd integers. Examples : Input : arr[] = {2, 5, 7, 8} Output : 3 Explanation : There are total 3 even-odd subarrays. 1) {2, 5} 2) {7, 8} 3) {2, 5, 7
    15+ min read
  • Generate an N-length array having equal count and sum of elements of both parities
    Given an integer N (3 ≤ N ≤ 105), the task is to generate an array of N distinct positive elements such that the count and sum of elements of both parties i.e even and odd, are the same. If it is not possible to construct such an array, print -1. Examples: Input: N = 8 Output: 2, 4, 6, 8, 1, 3, 5, 1
    6 min read
  • Count of subarrays of size K with elements having even frequencies
    Given an array arr[] and an integer K, the task is to count subarrays of size K in which every element appears an even number of times in the subarray. Examples: Input: arr[] = {1, 4, 2, 10, 2, 10, 0, 20}, K = 4 Output: 1 Explanation: Only subarray {2, 10, 2, 10} satisfies the required condition. In
    9 min read
  • Count unordered pairs of equal elements for all subarrays
    Given an array arr[] consisting of N integers, the task is to find the total number of unordered pairs (i, j) in the array such that arr[i] is equal to arr[j] and i < j for all subarrays of the given array. Examples: Input: arr[] = {1, 2, 1, 1}Output: 6Explanation: All subarrays of the given arra
    7 min read
  • Count non-overlapping Subarrays of size K with equal alternate elements
    Given an array arr[] of length N, the task is to find the count of non-overlapping subarrays of size K such that the alternate elements are equal. Examples: Input: arr[] = {2, 4, 2, 7}, K = 3Output: 1Explanation: Given subarray {2, 4, 2} is a valid array because the elements in even position(index n
    7 min read
  • Length of longest Subarray with equal number of odd and even elements
    Given an integer array arr[], the task is to find the length of the longest subarray with an equal number of odd and even elements. Examples: Input: arr[] = {1, 2, 1, 2}Output: 4 Explanation: Subarrays in the given array are - {{1}, {1, 2}, {1, 2, 1}, {1, 2, 1, 2}, {2}, {2, 1}, {2, 1, 2}, {1}, {1, 2
    12 min read
  • Program to print Sum of even and odd elements in an array
    Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index position
    13 min read
  • Number of permutations such that sum of elements at odd index and even index are equal
    Given N numbers, find the number of permutations in which the sum of elements at odd index and sum of elements at even index are equal. Examples: Input: 1 2 3 Output: 2 The permutations are: 1 3 2 sum at odd index = 1+2 = 3, sum at even index = 3 2 3 1 sum at odd index = 2+1 = 3, sum at even index =
    8 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