Sum of All Odd Length Subarrays - Problem
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.
For example, if arr = [1,4,2,5,3], the odd-length subarrays are:
- Length 1: [1], [4], [2], [5], [3]
- Length 3: [1,4,2], [4,2,5], [2,5,3]
- Length 5: [1,4,2,5,3]
We need to sum all elements in all these subarrays.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [1,4,2,5,3]
›
Output:
58
💡 Note:
Odd-length subarrays: [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. Sum = 1+4+2+5+3+7+11+10+15 = 58
Example 2 — Smaller Array
$
Input:
arr = [1,2]
›
Output:
3
💡 Note:
Only odd-length subarrays are [1] and [2]. Sum = 1 + 2 = 3
Example 3 — Single Element
$
Input:
arr = [10]
›
Output:
10
💡 Note:
Only one subarray [10] with odd length 1. Sum = 10
Constraints
- 1 ≤ arr.length ≤ 100
- 1 ≤ arr[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array with positive integers
2
Find Odd Subarrays
Identify all subarrays with odd lengths (1, 3, 5, ...)
3
Sum All Elements
Add up all elements from all odd-length subarrays
Key Takeaway
🎯 Key Insight: Each element contributes to multiple odd-length subarrays - count mathematically instead of generating all subarrays
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code