Sum of Absolute Differences in a Sorted Array — LeetCode 1685 Python Solution

MediumArrayMathPrefix Sum
Problem
#1685
Pattern
Prefix Sum
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:
        ans = []
        s, t = sum(nums), 0
        for i, x in enumerate(nums):
            v = x * i - t + s - t - x * (len(nums) - i)
            ans.append(v)
            t += x
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1685. Sum of Absolute Differences in a Sorted Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1685. Sum of Absolute Differences in a Sorted Array?
LeetCode 1685. Sum of Absolute Differences in a Sorted Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 1685. Sum of Absolute Differences in a Sorted Array?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 1685. Sum of Absolute Differences in a Sorted Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1685. Sum of Absolute Differences in a Sorted Array cover?
LeetCode 1685. Sum of Absolute Differences in a Sorted Array is tagged Array, Math and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview