array and hashmap May 24, 2023

Left and right sum differences

Time O(n) Space O(1) Open original problem

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)