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 Subarrays INPUT Array arr: 1 i=0 4 i=1 2 i=2 5 i=3 3 i=4 Odd-Length Subarrays: 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] Input: arr = [1, 4, 2, 5, 3] n = 5 elements Odd lengths: 1, 3, 5 ALGORITHM STEPS 1 Count Contribution Each element appears in multiple odd subarrays 2 Formula for count count = ((i+1)*(n-i)+1)/2 for element at index i 3 Calculate for each i Multiply element by its contribution count 4 Sum all contributions Add up all weighted element values Contribution Calculation: i=0: 1 x 3 = 3 i=1: 4 x 4 = 16 i=2: 2 x 5 = 10 i=3: 5 x 4 = 20 i=4: 3 x 3 = 9 count 3 4 5 4 3 FINAL RESULT Summing all contributions: 3 + 16 + 10 + 20 + 9 = 58 Total sum of odd subarrays Output: 58 OK - Verified Verification: Len 1: 1+4+2+5+3 = 15 Len 3: 7+11+10 = 28 Len 5: 15 15 + 28 + 15 = 58 Time: O(n), Space: O(1) Key Insight: Instead of generating all odd-length subarrays (O(n^2)), count how many times each element appears in odd-length subarrays. Element at index i appears in ((i+1)*(n-i)+1)/2 odd subarrays. This mathematical insight reduces time complexity from O(n^3) to O(n). TutorialsPoint - Sum of All Odd Length Subarrays | Optimal Solution O(n)
Asked in
Amazon 25 Google 18 Apple 12
98.5K 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