Difficulty: 🟢 Easy
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 indexi
in the arraynums
. If there is no such element,leftSum[i] = 0
.rightSum[i]
is the sum of elements to the right of the indexi
in the arraynums
. If there is no such element,rightSum[i] = 0
. Return the arrayanswer
.
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].
1 <= nums.length <= 1000
1 <= nums[i] <= 105
class Solution:
def leftRightDifference(self, nums: List[int]) -> List[int]:
right, left_sum, answer = 0, sum(nums), []
for num in nums:
right += num
answer.append(abs(right-left_sum))
left_sum -= num
return answer
The given solution calculates the array answer
by iteratively summing the elements from left to right and calculating the difference between the left and right sums at each index.
The algorithm works as follows:
- Initialize the variables
right
to 0,left_sum
to the sum of all elements innums
, and an empty arrayanswer
to store the results. - Iterate through each element
num
in thenums
array.- Add
num
to theright
sum. - Calculate the absolute difference between
right
andleft_sum
and append it to theanswer
array. - Subtract
num
from theleft_sum
.
- Add
- Return the
answer
array, which contains the absolute differences between the left and right sums at each index.
The algorithm calculates the left sum by subtracting the current element from the total sum and adds the current element to the right sum. It then calculates the absolute difference between the left and right sums and appends it to the answer
array.
The time complexity of this algorithm is O(n), where n is the length of the nums
array. The algorithm iterates through each element of nums
once and performs constant-time operations.
The space complexity of the algorithm is O(n) as it uses additional space to store the answer
array, which has the same length as nums
.
The given solution calculates the array answer
by iteratively summing the elements from left to right and calculating the difference between the left and right sums at each index. It has a time complexity of O(n) and a space complexity of O(n), making it an efficient solution for the problem at hand.
NB: If you want to get community points please suggest solutions in other languages as merge requests.