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:
Find an element in array such that sum of left array is equal to sum of right array
Next article icon

Count of elements such that difference between sum of left and right sub arrays is equal to a multiple of k

Last Updated : 02 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of length n and an integer k, the task is to find the number of indices from 2 to n-1 in an array having a difference of the sum of the left and right sub arrays equal to the multiple of the given number k.

Examples:  

Input: arr[] = {1, 2, 3, 3, 1, 1}, k = 4 
Output: 2 
Explanation: The only possible indices are 4 and 5

Input: arr[] = {1, 2, 3, 4, 5}, k = 1 
Output: 3  

Approach: 

  • Create a prefix array that contains the sum of the elements on the left and the suffix array which contains the sum of elements on the right. 
  • Check for every index the difference of the sum on the left and right and increase the counter if it is divisible by k.

Below is the implementation of the above approach: 

CPP




// C++ code to count of elements such that
// difference between the sum of left and right
// sub-arrays are equal to a multiple of k
 
#include <bits/stdc++.h>
using namespace std;
 
// Functions to find the no of elements
int noOfElement(int a[], int n, int k)
{
    // Creating a prefix array
    int prefix[n];
 
    // Starting element of prefix array
    // will be the first element
    // of given array
    prefix[0] = a[0];
    for (int i = 1; i < n; i++) {
        prefix[i] = prefix[i - 1] + a[i];
    }
 
    // Creating a suffix array;
    int suffix[n];
    // Last element of suffix array will
    // be the last element of given array
    suffix[n - 1] = a[n - 1];
    for (int i = n - 2; i >= 0; i--) {
        suffix[i] = suffix[i + 1] + a[i];
    }
 
    // Checking difference of left and right half
    // is divisible by k or not.
    int cnt = 0;
    for (int i = 1; i < n - 1; i++) {
        if ((prefix[i] - suffix[i]) % k == 0
            || (suffix[i] - prefix[i]) % k == 0) {
            cnt = cnt + 1;
        }
    }
 
    return cnt;
}
 
// Driver code
int main()
{
    int a[] = { 1, 2, 3, 3, 1, 1 };
    int k = 4;
    int n = sizeof(a) / sizeof(a[0]);
    cout << noOfElement(a, n, k);
    return 0;
}
 
 

Java




// Java code to count of elements such that
// difference between the sum of left and right
// sub-arrays are equal to a multiple of k
class GFG
{
 
// Functions to find the no of elements
static int noOfElement(int a[], int n, int k)
{
    // Creating a prefix array
    int []prefix = new int[n];
 
    // Starting element of prefix array
    // will be the first element
    // of given array
    prefix[0] = a[0];
    for (int i = 1; i < n; i++)
    {
        prefix[i] = prefix[i - 1] + a[i];
    }
 
    // Creating a suffix array;
    int []suffix = new int[n];
     
    // Last element of suffix array will
    // be the last element of given array
    suffix[n - 1] = a[n - 1];
    for (int i = n - 2; i >= 0; i--)
    {
        suffix[i] = suffix[i + 1] + a[i];
    }
 
    // Checking difference of left and right half
    // is divisible by k or not.
    int cnt = 0;
    for (int i = 1; i < n - 1; i++)
    {
        if ((prefix[i] - suffix[i]) % k == 0
            || (suffix[i] - prefix[i]) % k == 0)
        {
            cnt = cnt + 1;
        }
    }
    return cnt;
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = { 1, 2, 3, 3, 1, 1 };
    int k = 4;
    int n = a.length;
    System.out.print(noOfElement(a, n, k));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python




# Python3 code to count of elements such that
# difference between the sum of left and right
# sub-arrays are equal to a multiple of k
 
# Functions to find the no of elements
def noOfElement(a, n, k):
     
    # Creating a prefix array
    prefix = [0] * n
 
    # Starting element of prefix array
    # will be the first element
    # of given array
    prefix[0] = a[0]
    for i in range(1, n):
        prefix[i] = prefix[i - 1] + a[i]
 
    # Creating a suffix array
    suffix = [0] * n
     
    # Last element of suffix array will
    # be the last element of given array
    suffix[n - 1] = a[n - 1]
    for i in range(n - 2, -1, -1):
        suffix[i] = suffix[i + 1] + a[i]
 
    # Checking difference of left and right half
    # is divisible by k or not.
    cnt = 0
    for i in range(1, n - 1):
        if ((prefix[i] - suffix[i]) % k == 0 or (suffix[i] - prefix[i]) % k == 0):
            cnt = cnt + 1
 
    return cnt
 
# Driver code
 
a = [ 1, 2, 3, 3, 1, 1 ]
k = 4
n = len(a)
print(noOfElement(a, n, k))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# code to count of elements such that
// difference between the sum of left and right
// sub-arrays are equal to a multiple of k
using System;
 
class GFG
{
 
    // Functions to find the no of elements
    static int noOfElement(int []a, int n, int k)
    {
        // Creating a prefix array
        int []prefix = new int[n];
     
        // Starting element of prefix array
        // will be the first element
        // of given array
        prefix[0] = a[0];
        for (int i = 1; i < n; i++)
        {
            prefix[i] = prefix[i - 1] + a[i];
        }
     
        // Creating a suffix array;
        int []suffix = new int[n];
         
        // Last element of suffix array will
        // be the last element of given array
        suffix[n - 1] = a[n - 1];
        for (int i = n - 2; i >= 0; i--)
        {
            suffix[i] = suffix[i + 1] + a[i];
        }
     
        // Checking difference of left and right half
        // is divisible by k or not.
        int cnt = 0;
        for (int i = 1; i < n - 1; i++)
        {
            if ((prefix[i] - suffix[i]) % k == 0
                || (suffix[i] - prefix[i]) % k == 0)
            {
                cnt = cnt + 1;
            }
        }
        return cnt;
    }
     
    // Driver code
    public static void Main()
    {
        int []a = { 1, 2, 3, 3, 1, 1 };
        int k = 4;
        int n = a.Length;
        Console.Write(noOfElement(a, n, k));
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
// Javascript code to count of elements such that
// difference between the sum of left and right
// sub-arrays are equal to a multiple of k
     
// Functions to find the no of elements
function noOfElement(a,n,k)
{
    // Creating a prefix array
    let prefix = new Array(n);
   
    // Starting element of prefix array
    // will be the first element
    // of given array
    prefix[0] = a[0];
    for (let i = 1; i < n; i++)
    {
        prefix[i] = prefix[i - 1] + a[i];
    }
   
    // Creating a suffix array;
    let suffix = new Array(n);
       
    // Last element of suffix array will
    // be the last element of given array
    suffix[n - 1] = a[n - 1];
    for (let i = n - 2; i >= 0; i--)
    {
        suffix[i] = suffix[i + 1] + a[i];
    }
   
    // Checking difference of left and right half
    // is divisible by k or not.
    let cnt = 0;
    for (let i = 1; i < n - 1; i++)
    {
        if ((prefix[i] - suffix[i]) % k == 0
            || (suffix[i] - prefix[i]) % k == 0)
        {
            cnt = cnt + 1;
        }
    }
    return cnt;
}
     
    // Driver code   
    let a=[1, 2, 3, 3, 1, 1];
    let k = 4;
    let n = a.length;
    document.write(noOfElement(a, n, k));
       
 
 
// This code is contributed by patel2127
</script>
 
 
Output: 
2

 

Time Complexity: O(n), where n is the size of the array
Auxiliary Space: O(n), as extra space of size n is used to create prefix and suffix array



Next Article
Find an element in array such that sum of left array is equal to sum of right array

A

AmanGupta65
Improve
Article Tags :
  • Arrays
  • DSA
  • subarray
Practice Tags :
  • Arrays

Similar Reads

  • Count ways to split Array such that sum of max of left and min of right is at least K
    Given an array A[] consisting of N integers and an integer K. The task is to find the total number of ways in which you can divide the array into two parts such that the sum of the largest element in the left part and the smallest element in the right part is greater than or equal to K. Examples: In
    6 min read
  • Count possible removals to make absolute difference between the sum of odd and even indexed elements equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the number of times the absolute difference between the sum of elements at odd and even indices is K after removing any one element at a time from the given array. Examples: Input: arr[] = {2, 4, 2}, K = 2Output: 2Ex
    15+ min read
  • Find an element in array such that sum of left array is equal to sum of right array
    Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4
    15+ min read
  • Count ways to split array into pair of subsets with difference between their sum equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the number of ways to split the array into a pair of subsets such that the difference between their sum is K. Examples: Input: arr[] = {1, 1, 2, 3}, K = 1Output: 3Explanation:Following splits into a pair of subsets s
    15 min read
  • Count of elements such that its sum/difference with X also exists in the Array
    Given an array arr[] and an integer X, the task is to count the elements of the array such that their exist a element [Tex]arr[i] - X [/Tex]or [Tex]arr[i] + X [/Tex]in the array.Examples: Input: arr[] = {3, 4, 2, 5}, X = 2 Output: 4 Explanation: In the above-given example, there are 4 such numbers -
    9 min read
  • Find the difference of count of equal elements on the right and the left for each element
    Given an array arr[] of size N. The task is to find X - Y for each of the element where X is the count of j such that arr[i] = arr[j] and j > i. Y is the count of j such that arr[i] = arr[j] and j < i.Examples: Input: arr[] = {1, 2, 3, 2, 1} Output: 1 1 0 -1 -1 For index 0, X - Y = 1 - 0 = 1 F
    10 min read
  • Generate array having differences between count of occurrences of every array element on its left and right
    Given an array A[] consisting of N integers, the task is to construct an array B[] such that for every ith index, B[i] = X - Y, where X and Y are the count of occurrences of A[i] after and before the ith index. Examples: Input: A[] = {3, 2, 1, 2, 3}Output: 1 1 0 -1 -1Explanation: arr[0] = 3, X = 1,
    6 min read
  • Count pairs in an array such that the absolute difference between them is ≥ K
    Given an array arr[] and an integer K, the task is to find the count of pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? K. Note that (arr[i], arr[j]) and arr[j], arr[i] will be counted only once.Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 3 All valid pairs are (1, 3), (1
    6 min read
  • Total cuts such that sum of largest of left and smallest of right is atleast K
    Given an array A[] of size N and an integer K, the task is to find the total number of cuts that you can make such that for each cut these two conditions are satisfied: A cut divides an array into two parts of equal or unequal length (non-zero).Sum of the largest element in the left part and the sma
    6 min read
  • Maximize count of elements that can be selected having minimum difference between their sum and K
    Given an array arr[] and an integer value K, the task is to count the maximum number of array elements that can be selected such that: Sum of the selected array elements is less than K.K - (total sum of selected elements) is greater than or equal to 0 and minimum possible. Examples: Examples:Input:
    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