The "Sum of Distances" problem asks you to calculate a value for each element in an array based on other elements with the same value. For a given index i, you need to find all other indices j such that nums[i] == nums[j]. The value for index i is the sum of the absolute differences |i - j| for all such j. You must return an array of these sums.
Google and BNY Mellon ask this to test optimization skills. A brute-force approach (searching the whole array for each element) would be O(N²), which is unusable for large datasets. The problem requires the use of Hash Maps for grouping indices and Prefix Sums to calculate distances in linear time. It evaluates a candidate's ability to simplify mathematical summations.
The pattern is "Grouping with Prefix Sums."
[p1, p2, p3...pn], you need to calculate the sum of distances for each pi.pi, the sum of distances to indices on its left is (pi * count_left) - sum_left_indices, and for indices on its right, it's sum_right_indices - (pi * count_right).Array: [1, 3, 1, 1, 2]
[0, 2, 3].Master the "Contribution of distances" formula. It allows you to calculate the sum of distances from one point to a set of other points in O(1) time if you know the prefix sums of those points. This is a very powerful trick in geometry and array problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Subarray Sum With Length Divisible by K | Medium | Solve | |
| Minimum Array Changes to Make Differences Equal | Medium | Solve | |
| Count of Interesting Subarrays | Medium | Solve | |
| Maximum Good Subarray Sum | Medium | Solve | |
| Maximum Size Subarray Sum Equals k | Medium | Solve |