Sum of Absolute Differences in a Sorted Array - Problem

You are given an integer array nums sorted in non-decreasing order.

Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.

In other words, result[i] is equal to sum(|nums[i] - nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,5]
Output: [4,3,5]
💡 Note: For nums[0]=2: |2-3| + |2-5| = 1 + 3 = 4. For nums[1]=3: |3-2| + |3-5| = 1 + 2 = 3. For nums[2]=5: |5-2| + |5-3| = 3 + 2 = 5.
Example 2 — Single Element
$ Input: nums = [1]
Output: [0]
💡 Note: Only one element, so no other elements to compare with. Result is 0.
Example 3 — Larger Array
$ Input: nums = [1,4,6,8,10]
Output: [24,15,13,15,21]
💡 Note: For nums[0]=1: |1-4|+|1-6|+|1-8|+|1-10| = 3+5+7+9 = 24. Similar calculations for other elements give [24,15,13,15,21].

Constraints

  • 2 ≤ nums.length ≤ 105
  • nums is sorted in non-decreasing order
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Sum of Absolute Differences in Sorted Array INPUT Sorted Array nums: 2 i=0 3 i=1 5 i=2 Calculation Goal: result[0] = |2-3| + |2-5| = 1 + 3 = 4 result[1] = |3-2| + |3-5| = 1 + 2 = 3 result[2] = |5-2| + |5-3| = 3 + 2 = 5 O(n^2) naive approach Can we do better? YES! Use Prefix Sum ALGORITHM STEPS 1 Build Prefix Sum prefix[i] = sum of nums[0..i] 2 5 10 prefix[] 2 Calculate Left Sum leftSum = prefix[i-1] Sum of elements before i 3 Calculate Right Sum rightSum = total - prefix[i] Sum of elements after i 4 Compute Result result[i] = (i*nums[i] - leftSum) + (rightSum - (n-i-1)*nums[i]) Time: O(n) | Space: O(n) Prefix sum enables O(1) range sum FINAL RESULT For i=0 (nums[0]=2): left=0, right=8 0*2-0 + 8-2*2 = 0+4 = 4 For i=1 (nums[1]=3): left=2, right=5 1*3-2 + 5-1*3 = 1+2 = 3 For i=2 (nums[2]=5): left=5, right=0 2*5-5 + 0-0*5 = 5+0 = 5 Output Array: 4 3 5 OK - [4, 3, 5] Matches expected output Key Insight: Since the array is SORTED, for element at index i: all elements to the LEFT are smaller, all to the RIGHT are larger. This means |nums[i]-nums[j]| = nums[i]-nums[j] (left) or nums[j]-nums[i] (right). No actual absolute value needed! Using prefix sums, we can compute left/right sums in O(1), giving us overall O(n) time complexity. TutorialsPoint - Sum of Absolute Differences in a Sorted Array | Optimal Prefix Sum Approach
Asked in
Amazon 15 Microsoft 12 Google 8
23.5K Views
Medium Frequency
~25 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