Sum of Absolute Differences in a Sorted Array - Problem

You're given an integer array nums that's already sorted in non-decreasing order. Your task is to build a result array where each element represents the sum of absolute differences between the current element and all other elements in the array.

For each position i, calculate result[i] = sum(|nums[i] - nums[j]|) where j ranges from 0 to nums.length - 1 and j β‰  i.

Example: If nums = [2, 3, 5], then for nums[1] = 3:

  • |3 - 2| = 1
  • |3 - 5| = 2
  • result[1] = 1 + 2 = 3

The key insight is that since the array is already sorted, we can leverage mathematical properties to avoid the naive O(nΒ²) approach and solve this efficiently using prefix sums.

Input & Output

example_1.py β€” Basic Case
$ Input: [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.py β€” Single Element
$ Input: [1]
β€Ί Output: [0]
πŸ’‘ Note: With only one element, there are no other elements to compare with, so the sum of absolute differences is 0.
example_3.py β€” Equal Elements
$ Input: [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. The middle elements have smaller sums as they're closer to other elements.

Constraints

  • 2 ≀ nums.length ≀ 105
  • 1 ≀ nums[i] ≀ nums[i + 1] ≀ 104
  • Array is guaranteed to be sorted in non-decreasing order

Visualization

Tap to expand
Mathematical Optimization Insight23579Current: nums[2] = 5≀ 5β‰₯ 5For elements ≀ nums[i]:|nums[i] - left| = nums[i] - leftSum = nums[i] Γ— count - leftSumFor elements β‰₯ nums[i]:|nums[i] - right| = right - nums[i]Sum = rightSum - nums[i] Γ— countFinal Formula:result[i] = nums[i] Γ— (2Γ—i - n + 1) + rightSum - leftSum
Understanding the Visualization
1
Recognize Sorted Property
Since array is sorted, all elements left of index i are ≀ nums[i], all elements right are β‰₯ nums[i]
2
Simplify Absolute Values
For left elements: |nums[i] - left| = nums[i] - left. For right elements: |nums[i] - right| = right - nums[i]
3
Apply Mathematical Formula
Sum = (nums[i] Γ— count_left - left_sum) + (right_sum - nums[i] Γ— count_right)
4
Optimize with Running Sums
Track left_sum as we iterate, calculate right_sum = total_sum - left_sum - nums[i]
Key Takeaway
🎯 Key Insight: The sorted property eliminates the need for absolute value calculationsβ€”we know the relationship between current element and its neighbors, allowing us to use mathematical formulas instead of nested loops.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K 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