Sum of Absolute Differences in a Sorted Array

Medium Topics Company Tags

The integer array nums is sorted in non-decreasing order. Return an array of the same length whose entry at index i is the sum of abs(nums[i] - nums[j]) over every index j. Including j = i contributes zero. Preserve the original index order in the result.

Example 1:

Input: nums = [1,2,4]

Output: [4,3,5]

Explanation: For 1, the distances to 1, 2, and 4 sum to 0 + 1 + 3 = 4. For 2 they sum to 1 + 0 + 2 = 3, and for 4 they sum to 3 + 2 + 0 = 5.

Example 2:

Input: nums = [7,7]

Output: [0,0]

Explanation: Both values are 7, so every absolute difference is zero.

Example 3:

Input: nums = [1,1,3]

Output: [2,2,4]

Explanation: Each occurrence of 1 has total distance 0 + 0 + 2 = 2. The value 3 has total distance 2 + 2 + 0 = 4.

Constraints:

  • 2 <= nums.length <= 100000
  • 1 <= nums[i] <= 10000
  • nums is sorted in non-decreasing order.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.