File: sum-of-all-odd-length-subarrays/solution.py

Date: 2026-06-06

Time: 19:20

Purpose

This file solves LeetCode 1588: Sum of All Odd Length Subarrays. It computes the sum of every subarray of odd length (1, 3, 5, ...) from a given array of positive integers. Rather than enumerating subarrays (O(n^2) or O(n^3)), it uses an O(n) closed-form formula based on counting how many odd-length subarrays each element participates in.

Key Components

Solution.sumOddLengthSubarrays(self, arr: List[int]) -> int

The sole method. For each index i, it multiplies arr[i] by the number of odd-length subarrays that include position i, then sums the results.

The contribution count formula: ((i + 1) * (n - i) + 1) // 2

Patterns

Dependencies

Imports: typing.List — used only for the type annotation on arr.

Imported by: The test_solution.py in the same directory imports this Solution class. The massive "Imported By" list in the prompt is misleading — those are test files for *other* problems that happen to share the same import pattern, not actual consumers of this specific module.

Flow

1. Compute n = len(arr).

2. For each index i in [0, n):

3. Sum all contributions and return.

Invariants

Error Handling

None. The method trusts its input matches the LeetCode contract (non-empty array of positive integers). No bounds checking, no empty-array guard.

Topics to Explore

Beliefs