Problem Description
Given an integer array nums, for every index i compute the sum of the absolute differences |i - j| for all indices j (j ≠ i) where nums[j] equals nums[i]. If no such j exists, the result for index i is 0. Return the resulting array.
Key Insights
- Group indices by their corresponding values using a hash table.
- For each group of indices (which are naturally in sorted order), precompute prefix sums of indices for efficient range sum calculations.
- For each index at position i within the group, the sum of distances can be computed using:
- Left contribution: i * current_index - (sum of indices up to i-1)
- Right contribution: (sum of indices from i+1 to end) - (number_of_elements_after_i * current_index)
- Process each group independently and assign the computed value to the correct positions in the answer array.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the array (each index is processed once and prefix sums are computed in linear time per group). Space Complexity: O(n) to store the groups and prefix sum arrays.
Solution
We utilize a hash table (or dictionary) to group indices by the value in nums. For each group, we compute a prefix sum of indices. For an index at position i within a group with sorted indices, the distance sum is calculated as:
left_dist = (current_index * i) - (sum of all indices before i)
right_dist = (sum of all indices after i) - (current_index * (number of indices after i))
Adding left_dist and right_dist gives the total sum of distances for that index. We then place this result back into the output array at the proper index.