Leetcode 2574. Left and Right Sum Differences
Given a 0-indexed integer array nums
, find a 0-indexed integer array answer
where:
answer.length == nums.length
.answer[i] = |leftSum[i] - rightSum[i]|
.Where:
leftSum[i]
is the sum of elements to the left of index i
in the array nums
. If there is no such element, leftSum[i]
is 0
.rightSum[i]
is the sum of elements to the right of index i
in the array nums
. If there is no such element, rightSum[i]
is 0
.Return the answer
array.
Input: nums = [10,4,8,3]
Output: [15,1,11,22]
Explanation:
- For index 0, leftSum is [], rightSum is [4,8,3], and |0 - 15| = 15.
- For index 1, leftSum is [10], rightSum is [8,3], and |10 - 11| = 1.
- For index 2, leftSum is [10,4], rightSum is [3], and |14 - 3| = 11.
- For index 3, leftSum is [10,4,8], rightSum is [], and |22 - 0| = 22.
Input: nums = [1,2,3,4]
Output: [10,8,6,4]
Explanation:
- For index 0, leftSum is [], rightSum is [2,3,4], and |0 - 9| = 9.
- For index 1, leftSum is [1], rightSum is [3,4], and |1 - 7| = 6.
- For index 2, leftSum is [1,2], rightSum is [4], and |3 - 4| = 1.
- For index 3, leftSum is [1,2,3], rightSum is [], and |6 - 0| = 6.
leftSum
) and one for the cumulative right sums (rightSum
).answer
array.answer
array.public class Solution {
public int[] leftRightDifference(int[] nums) {
int n = nums.length;
int[] leftSum = new int[n];
int[] rightSum = new int[n];
int[] answer = new int[n];
// Calculate left sums
for (int i = 1; i < n; i++) {
leftSum[i] = leftSum[i - 1] + nums[i - 1];
}
// Calculate right sums
for (int i = n - 2; i >= 0; i--) {
rightSum[i] = rightSum[i + 1] + nums[i + 1];
}
// Calculate answer array
for (int i = 0; i < n; i++) {
answer[i] = Math.abs(leftSum[i] - rightSum[i]);
}
return answer;
}
}
O(n)
where n
is the length of the input array nums
. This is because we are iterating through the array three times: once for calculating leftSum
, once for calculating rightSum
, and once for computing the answer
.O(n)
due to the additional arrays leftSum
and rightSum
.This solution efficiently computes the required difference arrays with linear time complexity and minimal extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?