In this problem, you are given a sorted array of integers. For each element at index i, you need to calculate the sum of the absolute differences between that element and every other element in the array. For example, if the array is [1, 4, 6] and you are looking at the element '4', you need to compute |4-1| + |4-4| + |4-6| = 3 + 0 + 2 = 5. You must return an array of these sums.
Companies like Meta and Google ask this to see if a candidate can optimize a calculation from O(N²) to O(N). The sorted property of the array is a huge hint. It tests the candidate's ability to use mathematical properties of sums to avoid redundant calculations. It also tests the implementation of prefix sums, a core concept in array optimization.
The pattern used is Prefix Sums (or Cumulative Sums). Since the array is sorted, for any element nums[i], all elements to its left are smaller (or equal) and all elements to its right are larger (or equal).
(nums[i] * count_left) - sum_left.sum_right - (nums[i] * count_right).
By pre-calculating the total sum of the array, we can derive sum_left and sum_right in constant time as we iterate through the array.Array: [1, 4, 6]. Total Sum = 11.
sum_left = 1, count_left = 1. Difference = (4 * 1) - 1 = 3.sum_right = 6, count_right = 1. Difference = 6 - (4 * 1) = 2.sum_left = 0, count_left = 0. Difference = 0.sum_right = 10, count_right = 2. Difference = 10 - (1 * 2) = 8.Always pay attention to whether an array is sorted. If it is, absolute differences can almost always be simplified. Practice calculating prefix sums on the fly using a single variable (current_running_sum) to keep your space complexity at O(1) beyond the output array.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum of All Odd Length Subarrays | Easy | Solve | |
| Number of Sub-arrays With Odd Sum | Medium | Solve | |
| Continuous Subarray Sum | Medium | Solve | |
| Count the Hidden Sequences | Medium | Solve | |
| Number of Zero-Filled Subarrays | Medium | Solve |