Left and Right Sum Differences - Problem
You are given a 0-indexed integer array nums of size n.
Define two arrays leftSum and rightSum where:
leftSum[i]is the sum of elements to the left of the indexiin the arraynums. If there is no such element,leftSum[i] = 0.rightSum[i]is the sum of elements to the right of the indexiin the arraynums. If there is no such element,rightSum[i] = 0.
Return an integer array answer of size n where answer[i] = |leftSum[i] - rightSum[i]|.
Input & Output
Example 1 — Basic Four Elements
$
Input:
nums = [10,4,8,3]
›
Output:
[15,1,11,22]
💡 Note:
At i=0: leftSum=0, rightSum=4+8+3=15, |0-15|=15. At i=1: leftSum=10, rightSum=8+3=11, |10-11|=1. At i=2: leftSum=10+4=14, rightSum=3, |14-3|=11. At i=3: leftSum=10+4+8=22, rightSum=0, |22-0|=22.
Example 2 — Single Element
$
Input:
nums = [1]
›
Output:
[0]
💡 Note:
Only one element, so leftSum=0 and rightSum=0, difference is |0-0|=0.
Example 3 — Two Elements
$
Input:
nums = [2,3]
›
Output:
[3,2]
💡 Note:
At i=0: leftSum=0, rightSum=3, |0-3|=3. At i=1: leftSum=2, rightSum=0, |2-0|=2.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array [10,4,8,3] with positions marked
2
Calculate Sums
For each position, find left sum and right sum
3
Output Differences
Compute |leftSum - rightSum| for each position
Key Takeaway
🎯 Key Insight: Use totalSum - leftSum - currentElement to calculate rightSum efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code