
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 <= 1051 <= 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:
Understanding Absolute Differences:
- Given that the array is sorted, for a fixed
i, all elements beforeiare less than or equal tonums[i]and all elements afteriare greater than or equal tonums[i]. - Consequently, for any element
nums[i], the absolute difference with any prior elementnums[j]wherej < ican be simplified tonums[i] - nums[j]becausenums[i] >= nums[j]. - Similarly, for any follower element
nums[k]wherek > i, the absolute value ofnums[i] - nums[k]simply translates tonums[k] - nums[i]sincenums[k] >= nums[i].
- Given that the array is sorted, for a fixed
Constructing the Result Using Prefix and Suffix Sums:
- Prefix Sum Calculation: Create a prefix sum array where each element at index
iholds the sum of elements from the start of 'nums' array to thei-thelement. 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
prefixandsuffixsums, compute for eachithe contribution of all elements beforeiand all elements afteri, inO(1)time using these summations.
- Prefix Sum Calculation: Create a prefix sum array where each element at index
Final Calculation:
- For each index
i, calculate the sum of absolute differences with elements beforeiusing the prefix sum and with elements afteriusing the suffix sum. Summing these two givesresult[i].
- For each index
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++
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:
countto store the number of elements in the input array.sumAllto calculate the sum of all elements in the array usingstd::accumulate.sumLeftto keep a running sum of the elements processed so far from the left.- An empty
resultvector 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
countLeftandcountRight, representing the number of elements on the left and right of the current element, respectively. - Compute
totalLeftas the difference betweencountLefttimes the current element andsumLeft. - Calculate
totalRightas the difference betweensumRightandcountRighttimes the current element. - Add the sum of
totalLeftandtotalRightto theresultvector. - Update
sumLeftby adding the current element to it.
- Calculate
Return the
resultvector 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
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:
Initialize
elementCountto ascertain the number of elements in the array.Calculate
sumAllElementswhich is the total sum of all the elements in the array.Initialize
sumPreviousElementsto keep track of the sum of elements before the current index as the iterations proceed.Create an array
resultto store the results for each element.Use a loop to iterate through the array. For each element at the specified index:
- Calculate
sumFollowingElementswhich is the sum of the elements after the current index. previousCountandfollowingCountrespectively count the number of elements before and after the current index.- Compute
sumLeftDifference, which is the difference multiplied by the count of previous elements, minussumPreviousElements. - Calculate
sumRightDifference, which issumFollowingElementsless the product offollowingCounttimes the current element. - Sum the left and right differences and assign this value to the respective index in the
resultarray. - Update
sumPreviousElementsby adding the current element.
- Calculate
Return the
resultarray 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
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:
- Determine the length of
elementsand calculate the total sum of all elements. - Initialize
sum_to_leftto zero and prepare an empty listresultfor storing the final output. - 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_leftand the current element from thetotal_sum. - Define
count_to_leftas the current index andcount_to_rightas the number of elements to the right of the current element. - Compute
sum_left, the difference between the product ofcount_to_leftand the current element and thesum_to_left. - Compute
sum_right, the difference betweensum_to_rightand the product ofcount_to_rightand the current element. - Append the sum of
sum_leftandsum_rightto theresultlist. - Update
sum_to_leftby adding the current element to it.
- Calculate the sum to the right of the current element by subtracting
- Return the
resultlist 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.