Sum of Distances

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.

Note: This question is the same as 2121: Intervals Between Identical Elements.

Example 1
Inputnums = [1,3,1,1,2]
Output[5,0,3,4,0]
For each index, the sum is computed over distances to all other indices with the same value, giving [5, 0, 3, 4, 0].
Example 2
Inputnums = [0,5,3]
Output[0,0,0]
Since each element in nums is distinct, arr[i] = 0 for all i.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate