Sum of All Odd Length Subarrays — LeetCode 1588 Python Solution

EasyArrayMathPrefix Sum
Problem
#1588
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr. A subarray is a contiguous subsequence of the array.

Example

Input
arr = [1,4,2,5,3]
Output
58
Explanation
The odd-length subarrays of arr and their sums are:

Python solution

Python
class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        n = len(arr)
        f = [0] * n
        g = [0] * n
        ans = f[0] = arr[0]
        for i in range(1, n):
            f[i] = g[i - 1] + arr[i] * (i // 2 + 1)
            g[i] = f[i - 1] + arr[i] * ((i + 1) // 2)
            ans += f[i]
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1588. Sum of All Odd Length Subarrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1588. Sum of All Odd Length Subarrays?
LeetCode 1588. Sum of All Odd Length Subarrays is rated Easy on LeetCode.
What is the time complexity of LeetCode 1588. Sum of All Odd Length Subarrays?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1588. Sum of All Odd Length Subarrays?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1588. Sum of All Odd Length Subarrays cover?
LeetCode 1588. Sum of All Odd Length Subarrays is tagged Array, Math and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview