You're given an array of numbers where some values might appear multiple times. For each element in the array, imagine you want to calculate how far away it is from all other elements that have the same value.
More specifically, for each position i in the array, you need to find all other positions j where the values are equal (nums[i] == nums[j] but i โ j), then sum up all the distances |i - j| between these positions.
Goal: Return an array where each element represents the sum of distances from that position to all other positions with the same value.
Example: If nums = [1, 3, 1, 1, 2], then for the first element (value 1 at index 0), it appears again at indices 2 and 4. So the sum of distances is |0-2| + |0-4| = 2 + 4 = 6.
Input & Output
Visualization
Time & Space Complexity
For each of n elements, we scan through all n elements to find matches
Only using constant extra space for variables, excluding output array
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 109
- All array indices are 0-based