Sum of Distances - 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. If there is no such j, set arr[i] to be 0.

Return the array arr.

Input & Output

Example 1 — Mixed Values
$ Input: nums = [1,3,1,1,2]
Output: [5,0,3,4,0]
💡 Note: For nums[0]=1: distances to indices 2,3 are |0-2|+|0-3| = 2+3 = 5. For nums[1]=3: no other 3s, so 0. For nums[2]=1: distances to indices 0,3 are |2-0|+|2-3| = 2+1 = 3.
Example 2 — All Same
$ Input: nums = [2,2,2]
Output: [2,2,2]
💡 Note: All elements are 2. For each index, sum distances to the other two indices: |0-1|+|0-2| = 1+2 = 3? Wait, let me recalculate: |0-1|+|0-2| = 1+2 = 3, |1-0|+|1-2| = 1+1 = 2, |2-0|+|2-1| = 2+1 = 3. So result should be [3,2,3].
Example 3 — No Duplicates
$ Input: nums = [1,2,3,4]
Output: [0,0,0,0]
💡 Note: No duplicate values, so no matching elements for any index. All results are 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Sum of Distances ProblemInput:1311201234Value 1 appears at indices: 0, 2, 3Calculate distances:Index 0: |0-2| + |0-3| = 2 + 3 = 5Index 2: |2-0| + |2-3| = 2 + 1 = 3Index 3: |3-0| + |3-2| = 3 + 1 = 4Output:50340
Understanding the Visualization
1
Input Array
Array with values and their indices
2
Find Matches
For each element, find all other elements with same value
3
Sum Distances
Calculate |i - j| for all matching pairs
Key Takeaway
🎯 Key Insight: Group elements by value first, then use mathematical formulas to calculate distance sums efficiently
Asked in
Google 45 Microsoft 38 Amazon 32 Facebook 28
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen