Problem Description
Given a 0-indexed integer array arr, for every index i you must compute the sum of the absolute differences (intervals) between i and every other index where the value is equal to arr[i]. In other words, for each position, sum |i - j| for all indices j (j ≠ i) such that arr[j] == arr[i].
Key Insights
- Group array indices by their corresponding value.
- Use prefix sums to efficiently calculate the sum of intervals for indices in each group.
- For each sorted group, for an index at position i in the group, the contribution from indices to its left and right can be computed in O(1) time using prefix sums.
- The final answer for each index is computed by combining distances from left and right within its group.
Space and Time Complexity
Time Complexity: O(n) – Each element is processed once and each group’s intervals are computed in linear time. Space Complexity: O(n) – Additional space is used for storing groups and prefix sums over indices.
Solution
The solution groups indices by their array value using a hash table (or dictionary). For each group (which corresponds to a unique value), the indices are processed in sorted order. A prefix sum array is computed for the group. For each index at position i in the group, the sum of distances to the left is i * current_index - (sum of indices before i) and the sum of distances to the right is (sum of indices after i) - current_index * (number of indices to the right). The sum of these two values is the required output for that index. The computed intervals are stored in the result array.