Left and Right Sum Differences - Problem
You're given a 0-indexed integer array nums of size n. Your task is to calculate the balance at each position by finding the absolute difference between the sum of elements to the left and the sum of elements to the right.
Here's what you need to do:
- For each index
i, calculateleftSum[i]= sum of all elements before indexi - For each index
i, calculaterightSum[i]= sum of all elements after indexi - Return an array where
answer[i] = |leftSum[i] - rightSum[i]|
Example: For array [10, 4, 8, 3], at index 1 (value 4):
• Left sum = 10 (elements before index 1)
• Right sum = 8 + 3 = 11 (elements after index 1)
• Difference = |10 - 11| = 1
Input & Output
example_1.py — Basic Array
$
Input:
[10, 4, 8, 3]
›
Output:
[15, 1, 11, 22]
💡 Note:
At index 0: left=0, right=4+8+3=15, diff=15. At index 1: left=10, right=8+3=11, diff=1. At index 2: left=10+4=14, right=3, diff=11. At index 3: left=10+4+8=22, right=0, diff=22.
example_2.py — Single Element
$
Input:
[1]
›
Output:
[0]
💡 Note:
With only one element, there are no elements to the left or right, so leftSum=0, rightSum=0, and the difference is |0-0|=0.
example_3.py — All Zeros
$
Input:
[0, 0, 0, 0]
›
Output:
[0, 0, 0, 0]
💡 Note:
Since all elements are 0, all left sums and right sums are 0, resulting in differences of 0 at every position.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 105
- Follow-up: Can you solve this in O(1) extra space?
Visualization
Tap to expand
Understanding the Visualization
1
Setup
We have weights [10, 4, 8, 3] arranged in a line
2
Position 0
Standing at 10: left side empty (0), right side has 4+8+3=15, imbalance = 15
3
Position 1
Standing at 4: left side has 10, right side has 8+3=11, imbalance = |10-11| = 1
4
Position 2
Standing at 8: left side has 10+4=14, right side has 3, imbalance = |14-3| = 11
5
Position 3
Standing at 3: left side has 10+4+8=22, right side empty (0), imbalance = 22
Key Takeaway
🎯 Key Insight: Instead of recalculating sums repeatedly, we use the mathematical relationship that at any position, the right sum equals the total sum minus the left sum minus the current element. This transforms an O(n²) problem into an elegant O(n) solution!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code