Skip to content
Related Articles

Related Articles

Count of indices up to which prefix and suffix sum is equal for given Array

Improve Article
Save Article
Like Article
  • Last Updated : 03 Dec, 2021

Given an array arr[] of integers, the task is to find the number of indices up to which prefix sum and suffix sum are equal.

Example: 

Input: arr = [9, 0, 0, -1, 11, -1]
Output: 2
Explanation:  The indices up to which prefix and suffix sum are equal are given below:
At index 1 prefix and suffix sum are 9
At index 2 prefix and suffix sum are 9

Input: arr = [5, 0, 4, -1, -3, 0, 2, -2, 0, 3, 2]
Output: 3
Explanation:  The prefix subarrays and suffix subarrays with equal sum are given below:
At index 1 prefix and suffix sum are 5
At index 5 prefix and suffix sum are 5
At index 8 prefix and suffix sum are 5

 

Naive Approach: The given problem can be solved by traversing the array arr from left to right and calculating prefix sum till that index then iterating the array arr from right to left and calculating the suffix sum then checking if prefix and suffix sum are equal.
Time Complexity: O(N^2)

Approach: The above approach can be optimized by iterating the array arr twice. The idea is to precompute the suffix sum as the total subarray sum. Then iterate the array a second time to calculate prefix sum at every index then comparing the prefix and suffix sums and update the suffix sum. Follow the steps below to solve the problem:

  • Initialize a variable res to zero to calculate the answer
  • Initialize a variable sufSum to store the suffix sum
  • Initialize a variable preSum to store the prefix sum
  • Traverse the array arr and add every element arr[i] to sufSum
  • Iterate the array arr again at every iteration:
    • Add the current element arr[i] into preSum
    • If preSum and sufSum are equal then increment the value of res by 1
    • Subtract the current element arr[i] from sufSum
  • Return the answer stored in res

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate number of
// equal prefix and suffix sums
// till the same indices
int equalSumPreSuf(int arr[], int n)
{
 
    // Initialize a variable
    // to store the result
    int res = 0;
 
    // Initialize variables to
    // calculate prefix and suffix sums
    int preSum = 0, sufSum = 0;
 
    // Length of array arr
    int len = n;
 
    // Traverse the array from right to left
    for (int i = len - 1; i >= 0; i--)
    {
 
        // Add the current element
        // into sufSum
        sufSum += arr[i];
    }
 
    // Iterate the array from left to right
    for (int i = 0; i < len; i++)
    {
 
        // Add the current element
        // into preSum
        preSum += arr[i];
 
        // If prefix sum is equal to
        // suffix sum then increment res by 1
        if (preSum == sufSum)
        {
 
            // Increment the result
            res++;
        }
 
        // Subtract the value of current
        // element arr[i] from suffix sum
        sufSum -= arr[i];
    }
 
    // Return the answer
    return res;
}
 
// Driver code
int main()
{
 
    // Initialize the array
    int arr[] = {5, 0, 4, -1, -3, 0,
                 2, -2, 0, 3, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    // Call the function and
    // print its result
    cout << (equalSumPreSuf(arr, n));
}
 
// This code is contributed by Potta Lokesh

Java




// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to calculate number of
    // equal prefix and suffix sums
    // till the same indices
    public static int equalSumPreSuf(int[] arr)
    {
 
        // Initialize a variable
        // to store the result
        int res = 0;
 
        // Initialize variables to
        // calculate prefix and suffix sums
        int preSum = 0, sufSum = 0;
 
        // Length of array arr
        int len = arr.length;
 
        // Traverse the array from right to left
        for (int i = len - 1; i >= 0; i--) {
 
            // Add the current element
            // into sufSum
            sufSum += arr[i];
        }
 
        // Iterate the array from left to right
        for (int i = 0; i < len; i++) {
 
            // Add the current element
            // into preSum
            preSum += arr[i];
 
            // If prefix sum is equal to
            // suffix sum then increment res by 1
            if (preSum == sufSum) {
 
                // Increment the result
                res++;
            }
 
            // Subtract the value of current
            // element arr[i] from suffix sum
            sufSum -= arr[i];
        }
 
        // Return the answer
        return res;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initialize the array
        int[] arr = { 5, 0, 4, -1, -3, 0,
                      2, -2, 0, 3, 2 };
 
        // Call the function and
        // print its result
        System.out.println(equalSumPreSuf(arr));
    }
}

Python3




# Python implementation for the above approach
 
# Function to calculate number of
# equal prefix and suffix sums
# till the same indices
from builtins import range
 
def equalSumPreSuf(arr):
   
    # Initialize a variable
    # to store the result
    res = 0;
 
    # Initialize variables to
    # calculate prefix and suffix sums
    preSum = 0;
    sufSum = 0;
 
    # Length of array arr
    length = len(arr);
 
    # Traverse the array from right to left
    for i in range(length - 1,-1,-1):
       
        # Add the current element
        # into sufSum
        sufSum += arr[i];
 
    # Iterate the array from left to right
    for i in range(length):
 
        # Add the current element
        # into preSum
        preSum += arr[i];
 
        # If prefix sum is equal to
        # suffix sum then increment res by 1
        if (preSum == sufSum):
           
            # Increment the result
            res += 1;
 
        # Subtract the value of current
        # element arr[i] from suffix sum
        sufSum -= arr[i];
 
    # Return the answer
    return res;
 
# Driver code
if __name__ == '__main__':
   
    # Initialize the array
    arr = [5, 0, 4, -1, -3, 0, 2, -2, 0, 3, 2];
 
    # Call the function and
    # prits result
    print(equalSumPreSuf(arr));
 
    # This code is contributed by 29AjayKumar

C#




// C# implementation for the above approach
using System;
class GFG
{
 
    // Function to calculate number of
    // equal prefix and suffix sums
    // till the same indices
    static int equalSumPreSuf(int[] arr)
    {
 
        // Initialize a variable
        // to store the result
        int res = 0;
 
        // Initialize variables to
        // calculate prefix and suffix sums
        int preSum = 0, sufSum = 0;
 
        // Length of array arr
        int len = arr.Length;
 
        // Traverse the array from right to left
        for (int i = len - 1; i >= 0; i--) {
 
            // Add the current element
            // into sufSum
            sufSum += arr[i];
        }
 
        // Iterate the array from left to right
        for (int i = 0; i < len; i++) {
 
            // Add the current element
            // into preSum
            preSum += arr[i];
 
            // If prefix sum is equal to
            // suffix sum then increment res by 1
            if (preSum == sufSum) {
 
                // Increment the result
                res++;
            }
 
            // Subtract the value of current
            // element arr[i] from suffix sum
            sufSum -= arr[i];
        }
 
        // Return the answer
        return res;
    }
 
    // Driver code
    public static void Main()
    {
 
        // Initialize the array
        int[] arr = { 5, 0, 4, -1, -3, 0,
                      2, -2, 0, 3, 2 };
 
        // Call the function and
        // print its result
        Console.Write(equalSumPreSuf(arr));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




<script>
// Javascript code for the above approach
 
// Function to calculate number of
// equal prefix and suffix sums
// till the same indices
function equalSumPreSuf(arr, n)
{
 
    // Initialize a variable
    // to store the result
    let res = 0;
 
    // Initialize variables to
    // calculate prefix and suffix sums
    let preSum = 0, sufSum = 0;
 
    // Length of array arr
    let len = n;
 
    // Traverse the array from right to left
    for (let i = len - 1; i >= 0; i--)
    {
 
        // Add the current element
        // into sufSum
        sufSum += arr[i];
    }
 
    // Iterate the array from left to right
    for (let i = 0; i < len; i++)
    {
 
        // Add the current element
        // into preSum
        preSum += arr[i];
 
        // If prefix sum is equal to
        // suffix sum then increment res by 1
        if (preSum == sufSum)
        {
 
            // Increment the result
            res++;
        }
 
        // Subtract the value of current
        // element arr[i] from suffix sum
        sufSum -= arr[i];
    }
 
    // Return the answer
    return res;
}
 
// Driver code
 
// Initialize the array
let arr = [5, 0, 4, -1, -3, 0,
             2, -2, 0, 3, 2];
              
let n = arr.length
 
// Call the function and
// print its result
document.write(equalSumPreSuf(arr, n));
 
// This code is contributed by Samim Hossain Mondal.
</script>
Output
3

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!