714008. Equal Left and Right Subarray Sum
Easy
Equal Left and Right Subarray Sum
Summary
Given an array arr of integers, find all indices where the sum of elements to the left is equal to the sum of elements to the right. The problem involves arrays, prefix sums, and data structures.
Detailed Explanation
The problem requires us to find all indices in the array where the sum of elements to the left is equal to the sum of elements to the right. We can solve this by iterating over the array and maintaining a running total of the sum of elements to the left at each index.
Here's the step-by-step breakdown:
- Initialize two variables,
left_sumandright_sum, to 0. - Iterate over the array from left to right:
- For each element, add it to
left_sum. This gives us the sum of elements to the left at that index. - As we iterate, maintain a running total of the sum of elements to the right by subtracting each element from the previous
right_sum.
- For each element, add it to
- Check if
left_sumis equal toright_sum. If it is, then the current index satisfies the condition.
Here's an ASCII art diagram to illustrate the process:
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
left_sum: 0
right_sum: 0
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
left_sum: 1 (add 1)
right_sum: -1 (subtract 1)
...
Time complexity analysis:
- The algorithm iterates over the array once, resulting in a time complexity of O(n), where n is the length of the array.
Space complexity analysis:
- We only use a few extra variables to store
left_sumandright_sum, resulting in a space complexity of O(1).
Optimized Solutions
Java
public class Main {
public static void findEqualSubarray(int[] arr) {
int n = arr.length;
long left_sum = 0, right_sum = 0;
for (int i = 0; i < n; i++) {
left_sum += arr[i];
right_sum = 0;
for (int j = i + 1; j < n; j++) {
right_sum += arr[j];
}
if (left_sum == right_sum) {
System.out.println(i);
}
}
}
public static void main(String[] args) {
int[] arr = {1, 2, -3, 4, 5};
findEqualSubarray(arr);
}
}