LeetCode solutions

1693. Sum of All Odd Length Subarrays

My accepted Python solution to LeetCode problem 1693, Sum of All Odd Length Subarrays, running in 0ms.

  • Difficulty: Easy
  • Python
  • Runtime 0ms
  • Memory 17.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.2MB, accepted 2025-12-29.

python
class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        # For each element, count how many odd-length subarrays include it
        # Element at index i appears in subarrays starting at [0..i] and ending at [i..n-1]
        # Number of subarrays containing arr[i] = (i+1) * (n-i)
        # Half of them (rounded up) have odd length
        # Time: O(n), Space: O(1)
        n = len(arr)
        result = 0
        for i, val in enumerate(arr):
            total_subarrays = (i + 1) * (n - i)
            odd_subarrays = (total_subarrays + 1) // 2
            result += val * odd_subarrays
        return result

Source