Sum of All Odd Length Subarrays

Easy

Topics
ArrayPrefix SumMath

Given an array of positive integers arr, return the sum of all elements over all contiguous subarrays of odd length.

Example 1

nums14253
odd blocks11+4+21+4+2+5+344+2+522+5+353
Every contiguous block of odd length counts — length 1, 3, 5 and so on — and each is summed separately, so a value inside several blocks is added once per block. The answer adds up all of those sums: 58.
Top row is the input; the chips are its odd-length blocks.
Input:  arr = [1,4,2,5,3]
Output: 58

Example 2

nums12
odd blocks12
Input:  arr = [1,2]
Output: 3

Constraints

  • 1 <= arr.length <= 100
  • 1 <= arr[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

The straightforward reading is a double loop: fix a start, extend the end, and add the running sum whenever the length is odd. That is O(n^2), and with n <= 100 it is entirely adequate — which is what the shown solution does.

The O(n) solution is worth knowing because it is the more interesting idea. Instead of summing subarrays, ask how many odd-length subarrays contain each element, and multiply. An element at index i has i + 1 choices of start and n - i choices of end, so it appears in (i+1) * (n-i) subarrays in total. Of those, exactly half have odd length, rounded up:

count = (i + 1) * (n - i)
odd   = (count + 1) // 2
contribution = nums[i] * odd

💡 This is the contribution technique: rather than enumerating the groups and summing their members, enumerate the members and count the groups each belongs to. It turns many O(n^2) subarray sums into O(n).

Approach

  1. Fix each start, extend the end, maintain the running sum, and add it when the span length is odd.

Dry Run

nums = [1,4,2,5,3]

odd-length subarrays and their sums:
  length 1: [1]=1 [4]=4 [2]=2 [5]=5 [3]=3        -> 15
  length 3: [1,4,2]=7 [4,2,5]=11 [2,5,3]=10      -> 28
  length 5: [1,4,2,5,3]=15                        -> 15

answer 58

contribution check for index 0 (value 1):
  (0+1)*(5-0) = 5 subarrays contain it,
  (5+1)//2 = 3 of them odd -> contributes 1*3 = 3

Complexity

  • Time — O(n^2) as written; the contribution formula is O(n). Both pass at n <= 100, and the formula is the answer if the bound were larger.
  • Space — O(1): two accumulators.

Common Pitfalls

  • Recomputing sum(nums[i:j+1]) inside the inner loop, which makes it O(n^3). Carry the running sum instead.
  • Testing the length as j - i rather than j - i + 1.
  • In the contribution version, rounding the odd count down. With an odd total, the extra subarray is an odd-length one, so it rounds up.
  • Trying to use prefix sums to get O(n) while still enumerating every subarray. That removes the inner sum but not the O(n^2) enumeration.

Full Solution — all languages

class Solution:
    def sumOddLengthSubarrays(self, nums):
        n = len(nums)
        total = 0
        for i in range(n):
            s = 0
            for j in range(i, n):
                s += nums[j]
                if (j - i + 1) % 2 == 1:
                    total += s
        return total
SensAI
Beta
Tap the mic to stop voice mode