Sum of All Odd Length Subarrays - Problem

Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.

A subarray is a contiguous sequence of elements from the original array. For example, in array [1, 4, 2, 5, 3], the subarrays of length 1 are [1], [4], [2], [5], [3], the subarrays of length 3 are [1,4,2], [4,2,5], [2,5,3], and the subarray of length 5 is [1,4,2,5,3].

Your task: Find all subarrays with odd lengths (1, 3, 5, 7, ...), calculate the sum of each subarray, then return the total sum of all these sums.

Example: For arr = [1,4,2,5,3]:
• Length 1: [1], [4], [2], [5], [3] → sum = 15
• Length 3: [1,4,2], [4,2,5], [2,5,3] → sum = 7+11+10 = 28
• Length 5: [1,4,2,5,3] → sum = 15
• Total: 15 + 28 + 15 = 58

Input & Output

example_1.py — Basic Case
$ Input: [1,4,2,5,3]
Output: 58
💡 Note: Length 1: [1]+[4]+[2]+[5]+[3] = 15. Length 3: [1,4,2]+[4,2,5]+[2,5,3] = 7+11+10 = 28. Length 5: [1,4,2,5,3] = 15. Total: 15+28+15 = 58.
example_2.py — Small Array
$ Input: [1,2]
Output: 3
💡 Note: Only odd-length subarrays are of length 1: [1] and [2]. Sum = 1 + 2 = 3.
example_3.py — Single Element
$ Input: [10,11,12]
Output: 66
💡 Note: Length 1: [10]+[11]+[12] = 33. Length 3: [10,11,12] = 33. Total: 33+33 = 66.

Constraints

  • 1 ≤ arr.length ≤ 100
  • 1 ≤ arr[i] ≤ 1000
  • All integers in the array are positive

Visualization

Tap to expand
Understanding Odd-Length SubarraysExample: Array [1, 4, 2, 5, 3]14253Length 1 Subarrays (5 total):14253Sum = 15Length 3 Subarrays (3 total):142= 7425= 11253= 10Sum = 28Length 5 Subarray (1 total):14253Sum = 15Total Sum: 15 + 28 + 15 = 58💡 Key InsightInstead of generating all subarrays:• Calculate how many odd-length subarrays contain each element• For element at index i: Total subarrays = (left+1) × (right+1) Odd subarrays = ⌈total/2⌉• Time: O(n³) → O(n)
Understanding the Visualization
1
Identify positions
Each book (element) has a fixed position on the shelf
2
Count groupings
Calculate how many odd-sized groups can include each specific book
3
Apply formula
Use mathematical insight: (total_groups + 1) ÷ 2 gives odd-sized groups
Key Takeaway
🎯 Key Insight: Rather than generating all subarrays, we calculate each element's contribution mathematically. Each element appears in a predictable number of odd-length subarrays based on its position, leading to an elegant O(n) solution.
Asked in
Amazon 15 Microsoft 8 Google 6 Apple 4
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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