Sum of all odd length subarrays

January 1, 2023

array-and-hashmap

Problem URL: Sum of all odd length subarrays

We will generate all possible subarrays of odd length and sum them.

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        res = 0
        for i in range(len(arr)):
            for j in range(i, len(arr), 2):
                res += sum(arr[i:j + 1])
        return res

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

We can do this in one line too-

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        return sum(sum(arr[i:j + 1]) for i in range(len(arr)) for j in range(i, len(arr), 2))