Sum of All Odd Length Subarrays
Easy
Topics
Given an array of positive integers arr, return the sum of all elements over all contiguous subarrays of odd length.
Example 1
Input: arr = [1,4,2,5,3] Output: 58
Example 2
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
- 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 = 3Complexity
- 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 - irather thanj - 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 totalimport java.util.*;
class Solution {
public int sumOddLengthSubarrays(int[] nums) {
int n = nums.length, total = 0;
for (int i = 0; i < n; i++) {
int s = 0;
for (int j = i; j < n; j++) {
s += nums[j];
if ((j - i + 1) % 2 == 1) total += s;
}
}
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int sumOddLengthSubarrays(vector<int>& nums) {
int n = nums.size(), total = 0;
for (int i = 0; i < n; i++) {
int s = 0;
for (int j = i; j < n; j++) {
s += nums[j];
if ((j - i + 1) % 2 == 1) total += s;
}
}
return total;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var sumOddLengthSubarrays = function(nums) {
const n = nums.length;
let total = 0;
for (let i = 0; i < n; i++) {
let s = 0;
for (let j = i; j < n; j++) {
s += nums[j];
if ((j - i + 1) % 2 === 1) total += s;
}
}
return total;
};