Left and right sum differences

May 24, 2023

array-and-hashmap

Problem URL: Left and right sum differences

We will iterate over the array and compute the sum of the left and right subarrays as we iterate through. Then we will compute the difference between the sums and append it to our result. Finally we return our result.

class Solution:
    def leftRightDifference(self, nums: List[int]) -> List[int]:
        leftSum, rightSum = 0, sum(nums)
        res = []
        for num in nums:
            rightSum -= num
            res.append(abs(leftSum-rightSum))
            leftSum += num
        return res

Time complexity: O(n)
Space complexity: O(1)