Sum of Absolute Differences in a Sorted Array — LeetCode 1685 Python Solution
- Problem
- #1685
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array nums |
| Space | O(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.