Count of indices up to which prefix and suffix sum is equal for given Array
Last Updated :
23 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem