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,24]
💡 Note: For nums[0]=1: |1-4|+|1-6|+|1-8|+|1-10| = 3+5+7+9 = 24. Similar calculations for other elements.

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 ArrayInput:235Process:For 2: |2-3| + |2-5| = 1 + 3 = 4For 3: |3-2| + |3-5| = 1 + 2 = 3For 5: |5-2| + |5-3| = 3 + 2 = 5Output:435Each result[i] = sum of absolute differences with all other elements
Understanding the Visualization
1
Input
Sorted array nums = [2,3,5]
2
Process
For each element, sum |nums[i] - nums[j]| for all j ≠ i
3
Output
Array of sums [4,3,5]
Key Takeaway
🎯 Key Insight: Use the sorted property with prefix sums to calculate differences in O(n) time instead of O(n²)
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