Sum of All Odd Length Subarrays Problem
Description
LeetCode Problem 1588.
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.
Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[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
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66
Constraints:
1 <= arr.length <= 1001 <= arr[i] <= 1000
Follow up:
Could you solve this problem in O(n) time complexity?
Solution
Approach: Count Each Element's Contribution
Instead of listing subarrays, ask how many odd-length subarrays contain arr[i], and add arr[i] times that count.
A subarray containing index i starts at one of the i + 1 indices 0..i and ends at one of the n - i indices i..n-1, so there are (i + 1) * (n - i) of them. Its length is odd when the start and the end have the same parity. Among all start/end combinations, the odd-length ones are either exactly half or one more than half, which gives the count ((i + 1) * (n - i) + 1) / 2 (integer division).
For example, with arr = [1,4,2,5,3] the middle element 2 (at i = 2) is in 3 * 3 = 9 subarrays, and (9 + 1) / 2 = 5 of them have odd length: [2], [4,2,5], [1,4,2], [2,5,3] and the whole array.
Complexity: O(n) time and O(1) extra space.
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
n = len(arr)
ans = 0
for i, x in enumerate(arr):
# (i + 1) choices of start, (n - i) of end; a bit more than half give an odd length
ans += x * (((i + 1) * (n - i) + 1) // 2)
return ans