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 :
- Take a variable n which is of length of nums
- Take a variable s which is the sum of nums
- Create and initialize the result array with all 0’s
- Create a variable left and initialize it with 0
- Now traverse the anums array with i as index and num as values in it.
- Create a variable right and update it as s-left-num
- Now update result value as nums*(2*i-n+1)+right-left
- Subsequently keep on adding the num to the left element
- 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))