Leetcode #1588: Sum of All Odd Length Subarrays
In this guide, we solve Leetcode #1588 Sum of All Odd Length Subarrays in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Math, Prefix Sum
Intuition
Range queries become simple once we precompute cumulative sums.
We can transform subarray conditions into prefix comparisons.
Approach
Compute prefix sums and use a map to find matching prefixes.
This avoids nested loops while keeping the logic clear.
Steps:
- Compute prefix sums.
- Use a map to find valid ranges.
- Update the answer.
Example
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Python Solution
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.