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
Sum of All Odd Length SubarraysInput: [1,4,2,5,3]14253Length 1 subarrays:[1] + [4] + [2] + [5] + [3] = 15Length 3 subarrays:[1,4,2] + [4,2,5] + [2,5,3] = 7 + 11 + 10 = 28Length 5 subarrays:[1,4,2,5,3] = 15Output58Total: 15 + 28 + 15 = 58
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
Asked in
Amazon 25 Google 18 Apple 12
98.4K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen