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: [3,2,3]
💡 Note: All elements are 2. For each index, sum distances to the other two indices: |0-1|+|0-2| = 1+2 = 3, |1-0|+|1-2| = 1+1 = 2, |2-0|+|2-1| = 2+1 = 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 - Hash Approach INPUT nums = [1, 3, 1, 1, 2] i=0 i=1 i=2 i=3 i=4 1 3 1 1 2 Group by Value: 1 --> [0, 2, 3] 3 --> [1] 2 --> [4] For value 1 at index 0: |0-2| + |0-3| = 2 + 3 = 5 For value 1 at index 2: |2-0| + |2-3| = 2 + 1 = 3 For value 1 at index 3: |3-0| + |3-2| = 3 + 1 = 4 ALGORITHM STEPS 1 Build Hash Map Group indices by value 2 Prefix Sum Compute prefix sums 3 Calculate Distances Use prefix sums for O(1) 4 Build Result Store distances in arr For indices [0, 2, 3]: prefix = [0, 0, 2, 5] left_sum = prefix[k] right_sum = total - prefix[k+1] arr[i] = i*k - left_sum + right_sum - i*(n-k-1) where k = position in group FINAL RESULT Output Array: i=0 i=1 i=2 i=3 i=4 5 0 3 4 0 [5, 0, 3, 4, 0] Breakdown: arr[0]=5: |0-2|+|0-3|=5 arr[1]=0: only one 3 arr[2]=3: |2-0|+|2-3|=3 arr[3]=4: |3-0|+|3-2|=4 arr[4]=0: only one 2 OK - Complete! Key Insight: Use a hash map to group indices by their values, then use prefix sums to calculate the sum of distances in O(1) per element instead of O(n). For each group of indices, left distances = k*idx - prefix[k] and right distances = (total - prefix[k+1]) - idx*(n-k-1). TutorialsPoint - Sum of Distances | Hash Approach
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