Sum of Distances Problem
Description
LeetCode Problem 2615.
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. If there is no such j, set arr[i] to be 0.
Return the array arr.
Example 1:
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.
When i = 1, arr[1] = 0 because there is no other index with value 3.
When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3.
When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4.
When i = 4, arr[4] = 0 because there is no other index with value 2.
Example 2:
Input: nums = [0,5,3]
Output: [0,0,0]
Explanation: Since each element in nums is distinct, arr[i] = 0 for all i.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Note: This question is the same as 2121: Intervals Between Identical Elements.
Solution
Approach: Group Indices + Running Sums
Group the indices by value, so that idx lists the positions of one value in increasing order. Each group can be handled on its own.
For the first position idx[0], the distance to every other position in the group is idx[j] - idx[0], so the total to the right is sum(idx) - m * idx[0] where m = len(idx), and the total to the left is 0.
Moving from idx[i] to idx[i + 1] is a step of gap = idx[i + 1] - idx[i]. The i + 1 positions on the left each get gap farther away, so left += gap * (i + 1). The m - i - 1 positions on the right each get gap closer, so right -= gap * (m - i - 1). The answer for idx[i] is left + right.
Complexity: O(n) time and O(n) space, where n is the length of nums.
from collections import defaultdict
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