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 9Input: 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.
// 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)
{ int count = 0;
// Iterate over the array
for ( int i = 0; i < n; i++) {
int sum1 = 0, sum2 = 0;
// Find the left subarray sum
for ( int j = 0; j < i; j++) {
sum1 += arr[j];
}
// Find the right subarray sum
for ( int j = i + 1; j < n; j++) {
sum2 += arr[j];
}
// Check if both are equal
if (sum1 == sum2)
count++;
}
// Return the count
return count;
} // Driver code int main()
{ // Initialize the array
int arr[] = { 9, 0, 0, -1, 11, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
// Call the function and
// print its result
cout << (equalSumPreSuf(arr, n));
} |
import java.io.*;
import java.util.*;
public class Gfg {
public static int equalSumPreSuf( int [] arr, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
int sum1 = 0 , sum2 = 0 ;
for ( int j = 0 ; j < i; j++) {
sum1 += arr[j];
}
for ( int j = i + 1 ; j < n; j++) {
sum2 += arr[j];
}
if (sum1 == sum2)
count++;
}
return count;
}
public static void main(String[] args)
{
// Initialize the array
int [] arr = { 9 , 0 , 0 , - 1 , 11 , - 1 };
int n = arr.length;
// Call the function and
// print its result
System.out.println(equalSumPreSuf(arr, n));
}
} |
# Function to calculate number of # equal prefix and suffix sums # till the same indices def equalSumPreSuf(arr, n):
count = 0
# Iterate over the array
for i in range (n):
sum1 = 0
sum2 = 0
# Find the left subarray sum
for j in range (i):
sum1 + = arr[j]
# Find the right subarray sum
for j in range (i + 1 , n):
sum2 + = arr[j]
# Check if both are equal
if sum1 = = sum2:
count + = 1
# Return the count
return count
# Driver code arr = [ 9 , 0 , 0 , - 1 , 11 , - 1 ]
n = len (arr)
# Call the function and # print its result print (equalSumPreSuf(arr, n))
# This code is contributed by divya_p123. |
using System;
class Gfg {
// Function to calculate number of
// equal prefix and suffix sums
// till the same indices
static int equalSumPreSuf( int [] arr, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
int sum1 = 0, sum2 = 0;
for ( int j = 0; j < i; j++) {
sum1 += arr[j];
}
for ( int j = i + 1; j < n; j++) {
sum2 += arr[j];
}
if (sum1 == sum2)
count++;
}
return count;
}
// Driver code
static void Main()
{
// Initialize the array
int [] arr = { 9, 0, 0, -1, 11, -1 };
int n = arr.Length;
// Call the function and
// print its result
Console.WriteLine(equalSumPreSuf(arr, n));
}
} |
// Javascript code for the above approach // Function to calculate number of // equal prefix and suffix sums // till the same indices function equalSumPreSuf( arr, n)
{ let count = 0;
// Iterate over the array
for (let i = 0; i < n; i++) {
let sum1 = 0, sum2 = 0;
// Find the left subarray sum
for (let j = 0; j < i; j++) {
sum1 += arr[j];
}
// Find the right subarray sum
for (let j = i + 1; j < n; j++) {
sum2 += arr[j];
}
// Check if both are equal
if (sum1 == sum2)
count++;
}
// Return the count
return count;
} // Driver code // Initialize the array let arr = [ 9, 0, 0, -1, 11, -1 ]; let n = arr.length; // Call the function and // print its result console.log(equalSumPreSuf(arr, n)); // This code is contributed by agarwalpoojaa976. |
2
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Better Approach:
This approach to solve the problem is to precompute the prefix and suffix sum and store the result for both in different arrays. Now count the number of indices where prefix[i] == suffix[i]. This count will be our answer.
Algorithm:
- Initialize an array arr of n integers.
- Calculate the prefix sum of the array and store it in a vector prefix. The prefix sum of an element at index i is the sum of all the elements from index 0 to i.
- Calculate the suffix sum of the array and store it in a vector suffix. The suffix sum of an element at index i is the sum of all the elements from index i to n-1.
- Initialize a variable count to 0.
- Traverse the array and check if prefix[i] is equal to suffix[i]. If it is, then increment count.
- Return the count as the answer.
Below is the implementation of the approach:
// 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) {
// Calculate prefix sum
vector< int > prefix(n);
prefix[0] = arr[0];
for ( int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + arr[i];
}
// Calculate suffix sum
vector< int > suffix(n);
suffix[n - 1] = arr[n - 1];
for ( int i = n - 2; i >= 0; i--) {
suffix[i] = suffix[i + 1] + arr[i];
}
// Count the number of indices where prefix[i] == suffix[i]
int count = 0;
for ( int i = 0; i < n; i++) {
if (prefix[i] == suffix[i]) {
count++;
}
}
return count;
} 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));
return 0;
} |
import java.util.*;
public class Main {
// Function to calculate number of
// equal prefix and suffix sums
// till the same indices
static int equalSumPreSuf( int arr[], int n)
{
// Calculate prefix sum
int [] prefix = new int [n];
prefix[ 0 ] = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
prefix[i] = prefix[i - 1 ] + arr[i];
}
// Calculate suffix sum
int [] suffix = new int [n];
suffix[n - 1 ] = arr[n - 1 ];
for ( int i = n - 2 ; i >= 0 ; i--) {
suffix[i] = suffix[i + 1 ] + arr[i];
}
// Count the number of indices where prefix[i] ==
// suffix[i]
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (prefix[i] == suffix[i]) {
count++;
}
}
return count;
}
public static void main(String[] args)
{
// Initialize the array
int arr[] = { 5 , 0 , 4 , - 1 , - 3 , 0 , 2 , - 2 , 0 , 3 , 2 };
int n = arr.length;
// Call the function and
// print its result
System.out.println(equalSumPreSuf(arr, n));
}
} |
# Function to calculate number of # equal prefix and suffix sums # till the same indices def equalSumPreSuf(arr, n):
# Calculate prefix sum
prefix = [ 0 ] * n
prefix[ 0 ] = arr[ 0 ]
for i in range ( 1 , n):
prefix[i] = prefix[i - 1 ] + arr[i]
# Calculate suffix sum
suffix = [ 0 ] * n
suffix[n - 1 ] = arr[n - 1 ]
for i in range (n - 2 , - 1 , - 1 ):
suffix[i] = suffix[i + 1 ] + arr[i]
# Count the number of indices where prefix[i] == suffix[i]
count = 0
for i in range (n):
if prefix[i] = = suffix[i]:
count + = 1
# Returning result
return count
# test case arr = [ 5 , 0 , 4 , - 1 , - 3 , 0 , 2 , - 2 , 0 , 3 , 2 ]
n = len (arr)
print (equalSumPreSuf(arr, n))
|
// C# code 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, int n) {
// Calculate prefix sum
int [] prefix = new int [n];
prefix[0] = arr[0];
for ( int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + arr[i];
}
// Calculate suffix sum
int [] suffix = new int [n];
suffix[n - 1] = arr[n - 1];
for ( int i = n - 2; i >= 0; i--) {
suffix[i] = suffix[i + 1] + arr[i];
}
// Count the number of indices where prefix[i] == suffix[i]
int count = 0;
for ( int i = 0; i < n; i++) {
if (prefix[i] == suffix[i]) {
count++;
}
}
return count;
}
static void Main( string [] args){
// Initialize the array
int [] arr = {5, 0, 4, -1, -3, 0,
2, -2, 0, 3, 2};
int n = arr.Length;
// Call the function and
// print its result
Console.WriteLine(equalSumPreSuf(arr, n));
}
} |
// Function to calculate number of // equal prefix and suffix sums // till the same indices function equalSumPreSuf(arr, n) {
// Calculate prefix sum
let prefix = [];
prefix[0] = arr[0];
for (let i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + arr[i];
}
// Calculate suffix sum
let suffix = [];
suffix[n - 1] = arr[n - 1];
for (let i = n - 2; i >= 0; i--) {
suffix[i] = suffix[i + 1] + arr[i];
}
// Count the number of indices where prefix[i] == suffix[i]
let count = 0;
for (let i = 0; i < n; i++) {
if (prefix[i] == suffix[i]) {
count++;
}
}
return count;
} // Test case let arr = [5, 0, 4, -1, -3, 0, 2, -2, 0, 3, 2]; let n = arr.length; console.log(equalSumPreSuf(arr, n)); |
3
Time Complexity: O(N) where N is size of input array. This is because a for loop runs from 1 to N.
Space Complexity: O(N) as vectors prefix and suffix are created of size N where N is size of input array.
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++ 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 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));
}
} |
# 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
# print its result
print (equalSumPreSuf(arr));
# This code is contributed by 29AjayKumar
|
// 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. |
<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> |
3
Time Complexity: O(N)
Auxiliary Space: O(1)