Sum of Absolute Differences in a Sorted Array

Updated on 11 July, 2025
Sum of Absolute Differences in a Sorted Array header image

Problem Statement

Given an integer array, nums, which is sorted in non-decreasing order, your task is to construct a new integer array result of the same size. Each element in result, denoted as result[i], must represent the summation of the absolute differences between the element nums[i] and each of the other elements in the nums array. More specifically, for each i, compute result[i] as the sum of |nums[i] - nums[j]| for all j such that 0 <= j < nums.length and j != i.

Examples

Example 1

Input:

nums = [2,3,5]

Output:

[4,3,5]

Explanation:

Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.

Example 2

Input:

nums = [1,4,6,8,10]

Output:

[24,15,13,15,21]

Constraints

  • 2 <= nums.length <= 105
  • 1 <= nums[i] <= nums[i + 1] <= 104

Approach and Intuition

The key to solving this problem efficiently lies in understanding the terms involved in absolute differences in a sorted array. Here is a step-by-step approach to derive the solution:

  1. Understanding Absolute Differences:

    • Given that the array is sorted, for a fixed i, all elements before i are less than or equal to nums[i] and all elements after i are greater than or equal to nums[i].
    • Consequently, for any element nums[i], the absolute difference with any prior element nums[j] where j < i can be simplified to nums[i] - nums[j] because nums[i] >= nums[j].
    • Similarly, for any follower element nums[k] where k > i, the absolute value of nums[i] - nums[k] simply translates to nums[k] - nums[i] since nums[k] >= nums[i].
  2. Constructing the Result Using Prefix and Suffix Sums:

    • Prefix Sum Calculation: Create a prefix sum array where each element at index i holds the sum of elements from the start of 'nums' array to the i-th element. This allows for quick calculation of the sum of any subarray from the start to a given position.
    • Suffix Sum Calculation: Likewise, creating a suffix sum array helps determine the sum of elements from any position to the end of the array efficiently.
    • With prefix and suffix sums, compute for each i the contribution of all elements before i and all elements after i, in O(1) time using these summations.
  3. Final Calculation:

    • For each index i, calculate the sum of absolute differences with elements before i using the prefix sum and with elements after i using the suffix sum. Summing these two gives result[i].

By using this method, each result element is efficiently computed in constant time after the initial prefix and suffix arrays are built, resulting in a linear overall time complexity relative to the length of nums, which is vital given the constraints.

Understanding and applying these optimizations efficiently tackle the potential computational overhead, especially for larger arrays, within the prescribed limits.

Solutions

  • C++
cpp
class Solution {
public:
    vector<int> calculateDifferenceSums(vector<int>& elements) {
        int count = elements.size();
        int sumAll = accumulate(elements.begin(), elements.end(), 0);
            
        int sumLeft = 0;
        vector<int> result;
        for (int i = 0; i < count; i++) {
            int sumRight = sumAll - sumLeft - elements[i];
                
            int countLeft = i;
            int countRight = count - 1 - i;
                
            int totalLeft = countLeft * elements[i] - sumLeft;
            int totalRight = sumRight - countRight * elements[i];
                
            result.push_back(totalLeft + totalRight);
            sumLeft += elements[i];
        }
            
        return result;
    }
};

This solution involves computing the sum of absolute differences in a sorted array. Here's a breakdown of how the provided C++ code achieves this:

  • Initialize necessary variables:

    • count to store the number of elements in the input array.
    • sumAll to calculate the sum of all elements in the array using std::accumulate.
    • sumLeft to keep a running sum of the elements processed so far from the left.
    • An empty result vector to store the results.
  • Iterate through each element of the array:

    • Calculate sumRight, which is the sum of elements to the right of the current element.
    • Determine countLeft and countRight, representing the number of elements on the left and right of the current element, respectively.
    • Compute totalLeft as the difference between countLeft times the current element and sumLeft.
    • Calculate totalRight as the difference between sumRight and countRight times the current element.
    • Add the sum of totalLeft and totalRight to the result vector.
    • Update sumLeft by adding the current element to it.
  • Return the result vector containing the calculated values.

The core logic revolves around leveraging the sorted nature of the array to efficiently compute the sums of absolute differences for each element relative to all other elements. By keeping track of the sums and counts of elements to the left and right of the current element, the solution ensures optimal performance.

  • Java
java
class Solution {
    public int[] calculateAbsoluteDifferences(int[] elements) {
        int elementCount = elements.length;
        int sumAllElements = 0;
        for (int element : elements) {
            sumAllElements += element;
        }
            
        int sumPreviousElements = 0;
        int[] result = new int[elementCount];
        for (int index = 0; index < elementCount; index++) {
            int sumFollowingElements = sumAllElements - sumPreviousElements - elements[index];
                
            int previousCount = index;
            int followingCount = elementCount - index - 1;
                
            int sumLeftDifference = previousCount * elements[index] - sumPreviousElements;
            int sumRightDifference = sumFollowingElements - followingCount * elements[index];
                
            result[index] = sumLeftDifference + sumRightDifference;
            sumPreviousElements += elements[index];
        }
            
        return result;
    }
}

The provided solution details a method for computing the sum of absolute differences for each element in a sorted array. Here's a breakdown of how the method functions:

  1. Initialize elementCount to ascertain the number of elements in the array.

  2. Calculate sumAllElements which is the total sum of all the elements in the array.

  3. Initialize sumPreviousElements to keep track of the sum of elements before the current index as the iterations proceed.

  4. Create an array result to store the results for each element.

  5. Use a loop to iterate through the array. For each element at the specified index:

    • Calculate sumFollowingElements which is the sum of the elements after the current index.
    • previousCount and followingCount respectively count the number of elements before and after the current index.
    • Compute sumLeftDifference, which is the difference multiplied by the count of previous elements, minus sumPreviousElements.
    • Calculate sumRightDifference, which is sumFollowingElements less the product of followingCount times the current element.
    • Sum the left and right differences and assign this value to the respective index in the result array.
    • Update sumPreviousElements by adding the current element.
  6. Return the result array containing the desired sums of absolute differences for each element.

This algorithm efficiently leverages cumulative sums to calculate the required differences, ensuring each element’s result depends on previously computed totals, thus optimizing the performance by avoiding redundant recalculations.

  • Python
python
class Solution:
    def calcSumOfAbsDifferences(self, elements: List[int]) -> List[int]:
        size = len(elements)
        total_sum = sum(elements)
        sum_to_left = 0
        result = []
    
        for index in range(len(elements)):
            sum_to_right = total_sum - sum_to_left - elements[index]
                
            count_to_left = index
            count_to_right = size - 1 - index
                
            sum_left = count_to_left * elements[index] - sum_to_left
            sum_right = sum_to_right - count_to_right * elements[index]
    
            result.append(sum_left + sum_right)
            sum_to_left += elements[index]
            
        return result

The given Python solution calculates the sum of absolute differences for each element in a sorted array. The function calcSumOfAbsDifferences takes a list of integers (elements) and returns a new list with the computed result. Below, understand each step that this function executes:

  1. Determine the length of elements and calculate the total sum of all elements.
  2. Initialize sum_to_left to zero and prepare an empty list result for storing the final output.
  3. Iterate over all elements in the input list to compute the sum of absolute differences for each element:
    • Calculate the sum to the right of the current element by subtracting sum_to_left and the current element from the total_sum.
    • Define count_to_left as the current index and count_to_right as the number of elements to the right of the current element.
    • Compute sum_left, the difference between the product of count_to_left and the current element and the sum_to_left.
    • Compute sum_right, the difference between sum_to_right and the product of count_to_right and the current element.
    • Append the sum of sum_left and sum_right to the result list.
    • Update sum_to_left by adding the current element to it.
  4. Return the result list containing the sum of absolute differences for each element.

This implementation efficiently uses a single loop to manage the calculations, leveraging the properties of sorted arrays to optimize the computation of differences.

Comments

No comments yet.