Sum of Distances — LeetCode 2615 Python Solution

MediumArrayHash TablePrefix Sum
Problem
#2615
Pattern
Prefix Sum
Reading time
3 min

The problem

You are given a 0-indexed integer array nums. There exists an array arr of length nums.length, where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i.

Example

Input
nums = [1,3,1,1,2]
Output
[5,0,3,4,0]
Explanation
When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5.

Python solution

Python
class Solution:
    def distance(self, nums: List[int]) -> List[int]:
        d = defaultdict(list)
        for i, x in enumerate(nums):
            d[x].append(i)
        ans = [0] * len(nums)
        for idx in d.values():
            left, right = 0, sum(idx) - len(idx) * idx[0]
            for i in range(len(idx)):
                ans[idx[i]] = left + right
                if i + 1 < len(idx):
                    left += (idx[i + 1] - idx[i]) * (i + 1)
                    right -= (idx[i + 1] - idx[i]) * (len(idx) - i - 1)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2615. Sum of Distances is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

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 2615. Sum of Distances?
LeetCode 2615. Sum of Distances is rated Medium on LeetCode.
What is the time complexity of LeetCode 2615. Sum of Distances?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2615. Sum of Distances?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2615. Sum of Distances cover?
LeetCode 2615. Sum of Distances is tagged Array, Hash Table 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