Count of indices up to which prefix and suffix sum is equal for given Array
Last Updated :
19 Sep, 2023
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.
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)
{
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));
}
Java
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));
}
}
Python3
# 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.
C#
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
// 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.
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++
// 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;
}
Java
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));
}
}
Python3
# 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#
// 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));
}
}
JavaScript
// 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));
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++
// 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
# print its 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>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Count of indices for which the prefix and suffix product are equal
Given an array arr[] of integers, the task is to find the number of indices for which the prefix product and the suffix product are equal. Example: Input: arr = [4, -5, 1, 1, -2, 5, -2]Output: 2Explanation: The indices on which the prefix and the suffix product are equal are given below:At index 2 p
14 min read
Count pair of indices in Array having equal Prefix-MEX and Suffix-MEX
Given an array arr[] of N elements, the task is to find the number of pairs of indices such that the Prefix-MEX of the one index is equal to the Suffix-MEX of the other index. Order of indices in pair matters. MEX of an array refers to the smallest missing non-negative integer of the array. For the
10 min read
Count pairs of indices having equal prefix and suffix sums
Given an array arr[] of length N, the task is to find the count of pairs of indices (i, j) (0-based indexing) such that prefix sum of the subarray {arr[0], ... arr[i]} is equal to the suffix sum of the subarray {arr[N - 1], ..., arr[j]} ( 0 ? i, j < N). Examples: Input: arr[] = {1, 2, 1, 1}Output
6 min read
Index with Minimum sum of prefix and suffix sums in an Array
Given an array of integers. The task is to find the index i in the array at which the value of prefixSum(i) + suffixSum(i) is minimum.Note: PrefixSum(i) = The sum of first i numbers of the array.SuffixSum(i) = the sum of last N - i + 1 numbers of the array.1-based indexing is considered for the arra
10 min read
Count of elements which is the sum of a subarray of the given Array
Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
7 min read
Count of indices in Array having all prefix elements less than all in suffix
Given an array arr[], the task is to calculate the total number of indices where all elements in the left part is less than all elements in the right part of the array. Examples: Input: arr[] = {1, 5, 4, 2, 3, 8, 7, 9}Output: 3Explanation: Lets consider left part = [1], right part = [5, 4, 2, 3, 8,
12 min read
Count pairs in given Array having sum of index and value at that index equal
Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0â¤i<jâ¤n-1. Examples: Input: arr[] = { 6, 1, 4, 3 }Output: 3Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}. Input: a
8 min read
Count of subsequences in an array with sum less than or equal to X
Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100
13 min read
3 Sum - Count Triplets With Given Sum In Sorted Array
Given a sorted array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. More specifically, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k.Examp
10 min read
Number of Good Pairs - Count of index pairs with equal values in an array
Given an array of n elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i < jExamples : Input: arr = [5, 2, 3, 5, 5, 3]Output: 4Explanation: There are 4 good pairs (0, 3), (0, 4), (3, 4), (2, 5)Input: arr = [1, 1, 1, 1]Output: 6Explanation: All 6 pairs
6 min read