Sum of absolute differences in a sorted array

Updated

You are given an integer array which is  sorted in non-decreasing order. Build and return an integer array result with the same length as the integer array  such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.

Example 1 :
Input : nums = [2,3,5]
Output : [4,3,5]
Explanation : Assuming the arrays are 0-indexed, then

result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,

result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,

result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.

Example 2 :
Input : nums = [1,4,6,8,10]
Output : [24,15,13,15,21]

Approach :

  1. Take a variable n which is of length of nums
  2. Take a variable s which is the sum of nums
  3. Create and initialize the result array with all  0’s
  4. Create a variable left and initialize it with 0
  5. Now traverse the anums array with i as index and num as values in it.
  6. Create a variable right and update it as s-left-num
  7. Now update result value as nums*(2*i-n+1)+right-left
  8. Subsequently keep on adding the num to the left element
  9. Return the final result

Time Complexity : O(N)
Space Complexity : O(N)

Below is the implementation:

def getSumAbsoluteDifferences(nums):
    n = len(nums) # take a variable n which is of length of nums
    s = sum(nums) # take a variable s which is the sum of nums

    result = [0] * n # create and initialize the result array with all  0's 
    left = 0 # create a variable left and initialize it with 0
    for i, num in enumerate(nums): # now traverse the anums array with i as index and num as values in it.
        right = s - left - num # create a variavle right and update it as s-left-num
        result[i] = -left + right + num * (2*i - n + 1) # now update result value as nums*(2*i-n+1)+right-left
        left += num # subsequently keep on adding the num to the left element 

    return result #return the fianl result
  
  
nums = [2,3,5]
print(getSumAbsoluteDifferences(nums))

Output

[4, 3, 5]
Comment
Next tutorial
Mithlesh Upadhyay Published 4 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials