Leetcode problem 39 - 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 the index i in the array nums. If there is no such element, leftSum[i] = 0. rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0. Return the array answer.
Example 1:
Input: nums = [10,4,8,3] Output: [15,1,11,22] Explanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. Example 2:
Input: nums = [1] Output: [0] Explanation: The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0].
/**
* @param {number[]} nums
* @return {number[]}
*/
var leftRightDifference = function (nums) {
let leftSum = [];
let rightSum = [];
for (let i = 0; i < nums.length; i++) {
if (i === 0) {
leftSum[i] = 0;
} else {
leftSum[i] = leftSum[i - 1] + nums[i - 1];
}
}
for (let i = nums.length - 1; i >= 0; i--) {
if (i === nums.length - 1) {
rightSum[i] = 0;
} else {
rightSum[i] = rightSum[i + 1] + nums[i + 1];
}
}
for (let i = 0; i < nums.length; i++) {
nums[i] = Math.abs(leftSum[i] - rightSum[i]);
}
return nums;
};
let leftSum = [];
and let rightSum = [];
: Initialize two empty arrays, leftSum
and rightSum
, which will be used to store the cumulative sums of elements to the left and right of each element in the nums
array, respectively.
First Loop (Calculating leftSum):
for (let i = 0; i < nums.length; i++) {
: Start a loop that iterates over each element in the nums array.
if (i === 0) {
: Check if the current index is 0 (first element).
leftSum[i] = 0
: For the first element, set its leftSum
to 0.
leftSum[i] = leftSum[i - 1] + nums[i - 1]
: For other elements, calculate the cumulative sum by adding the previous element’s leftSum value and the corresponding element from the nums
array.
Second Loop (Calculating rightSum):
for (let i = nums.length - 1; i >= 0; i--) {
: Start a loop that iterates over each element in the nums
array in reverse order.
if (i === nums.length - 1) {: Check if the current index is the last index (last element).
rightSum[i] = 0
: For the last element, set its rightSum
to 0.
rightSum[i] = rightSum[i + 1] + nums[i + 1]
: For other elements, calculate the cumulative sum by adding the next element’s rightSum
value and the corresponding element from the nums
array.
Third Loop (Calculating absolute differences and modifying nums):
for (let i = 0; i < nums.length; i++) {
: Start a loop that iterates over each element in the nums
array.
nums[i] = Math.abs(leftSum[i] - rightSum[i])
: Calculate the absolute difference between leftSum[i]
and rightSum[i]
and store the result back in the nums
array.
return nums;
: Return the modified nums array containing the absolute differences.
Leave a comment