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 index i in the array nums. If there is no such element, leftSum[i] = 0.
  • rightSum[i] is the sum of elements to the right of the index i in the array nums. 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
Left and Right Sum DifferencesFor each position, calculate |leftSum - rightSum|10483i=0i=1i=2i=3L:0R:15L:10R:11L:14R:3L:22R:01511122Result: [15, 1, 11, 22]
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
Asked in
Amazon 15 Microsoft 8
25.0K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen