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 Differences INPUT nums array (0-indexed) 10 i=0 4 i=1 8 i=2 3 i=3 leftSum[i]: Sum of elements LEFT of i 0 10 14 22 rightSum[i]: Sum of elements RIGHT of i 15 11 3 0 Total sum = 10+4+8+3 = 25 ALGORITHM STEPS 1 Calculate Total Sum total = 10+4+8+3 = 25 2 Initialize Variables leftSum = 0 rightSum = total = 25 3 Iterate and Update For each i: rightSum -= nums[i] ans[i] = |left - right| leftSum += nums[i] 4 Compute Each Index i=0: |0-15|=15 i=1: |10-11|=1 i=2: |14-3|=11 i=3: |22-0|=22 O(n) time, O(1) space FINAL RESULT answer array 15 1 11 22 Breakdown: answer[0] = |0 - 15| = 15 answer[1] = |10 - 11| = 1 answer[2] = |14 - 3| = 11 answer[3] = |22 - 0| = 22 Output: [15, 1, 11, 22] OK - Verified Key Insight: Instead of computing leftSum and rightSum separately for each index (O(n^2)), we maintain running sums. rightSum starts as total and decreases; leftSum starts at 0 and increases. TutorialsPoint - Left and Right Sum Differences | Optimal Solution
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