2615. Sum of Distances
Medium
485
68

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 == nums and nums == nums. Therefore, arr = |0 - 2| + |0 - 3| = 5.
When i = 1, arr = 0 because there is no other index with value 3.
When i = 2, nums == nums and nums == nums. Therefore, arr = |2 - 0| + |2 - 3| = 3.
When i = 3, nums == nums and nums == nums. Therefore, arr = |3 - 0| + |3 - 2| = 4.
When i = 4, arr = 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 <= 105`
• `0 <= nums[i] <= 109`
Accepted
12.7K
Submissions
42.8K
Acceptance Rate
29.7%

Seen this question in a real interview before?
1/4
Yes
No

Discussion (0)

Related Topics