Given an integer array, find an index that divides it into two non-empty subarrays having an equal sum.

For example, consider array {-1, 6, 3, 1, -2, 3, 3}. The element 3 at index 2 divides it into two non-empty subarrays {-1, 6} and {1, -2, 3, 3} having the same sum. Please note that the problem specifically targets subarrays that are contiguous (i.e., occupy consecutive positions) and inherently maintains the order of elements.

Practice this problem

 
A naive solution would calculate the sum of the left and right subarray for each array element and print the index if both sums are the same. The time complexity of this approach O(n2), where n is the size of the input.

 
We can solve this problem in O(n) time by using extra space. The idea is to preprocess the array and store the sum of every index’s left and right subarray in two auxiliary arrays. Then we can calculate the left and right sum in constant time for any index.

To improve the space complexity to constant, preprocess the given array and store the sum of all array elements in a variable. Then traverse the array and maintain another variable to store the left subarray sum till the current item. Now we can calculate the right subarray sum in constant time by using the following formula:

Right subarray sum = Sum of all elements – (Current element + Left subarray sum)

 
The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The index is 2

Java


Download  Run Code

Output:

The index is 2

Python


Download  Run Code

Output:

The index is 2