
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:
Understanding Absolute Differences:
- Given that the array is sorted, for a fixed
i
, all elements beforei
are less than or equal tonums[i]
and all elements afteri
are greater than or equal tonums[i]
. - Consequently, for any element
nums[i]
, the absolute difference with any prior elementnums[j]
wherej < i
can 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
i
holds the sum of elements from the start of 'nums' array to thei-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
andsuffix
sums, compute for eachi
the contribution of all elements beforei
and 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 beforei
using the prefix sum and with elements afteri
using 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:
count
to store the number of elements in the input array.sumAll
to calculate the sum of all elements in the array usingstd::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
andcountRight
, representing the number of elements on the left and right of the current element, respectively. - Compute
totalLeft
as the difference betweencountLeft
times the current element andsumLeft
. - Calculate
totalRight
as the difference betweensumRight
andcountRight
times the current element. - Add the sum of
totalLeft
andtotalRight
to theresult
vector. - Update
sumLeft
by adding the current element to it.
- Calculate
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
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
elementCount
to ascertain the number of elements in the array.Calculate
sumAllElements
which is the total sum of all the elements in the array.Initialize
sumPreviousElements
to keep track of the sum of elements before the current index as the iterations proceed.Create an array
result
to store the results for each element.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
andfollowingCount
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, minussumPreviousElements
. - Calculate
sumRightDifference
, which issumFollowingElements
less the product offollowingCount
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.
- Calculate
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
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
elements
and calculate the total sum of all elements. - Initialize
sum_to_left
to zero and prepare an empty listresult
for 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_left
and the current element from thetotal_sum
. - Define
count_to_left
as the current index andcount_to_right
as the number of elements to the right of the current element. - Compute
sum_left
, the difference between the product ofcount_to_left
and the current element and thesum_to_left
. - Compute
sum_right
, the difference betweensum_to_right
and the product ofcount_to_right
and the current element. - Append the sum of
sum_left
andsum_right
to theresult
list. - Update
sum_to_left
by adding the current element to it.
- Calculate the sum to the right of the current element by subtracting
- 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.
No comments yet.