algoadvance

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

A subarray is a contiguous subsequence of the array.

Return the sum of all odd-length subarrays of arr.

Example:

Example 1:

Example 2:

Example 3:

Constraints:

Clarifying Questions

  1. Should we consider subarrays of length 1? (Yes, because they are of odd length)
  2. Is the sum guaranteed to fit within standard integer range in Python? (Yes, Python integers can handle large sums).

Strategy

  1. Iterate over all possible starting indices of the subarray.
  2. For each starting index, create subarrays of increasing odd lengths.
  3. Calculate the sum of each odd-length subarray and add it to a running total.

Code

def sumOddLengthSubarrays(arr):
    total_sum = 0
    n = len(arr)
    
    for i in range(n):
        current_sum = 0
        for j in range(i, n):
            current_sum += arr[j]
            if (j - i) % 2 == 0:  # Check for odd length
                total_sum += current_sum

    return total_sum

# Test Cases
print(sumOddLengthSubarrays([1,4,2,5,3]))  # Expected output: 58
print(sumOddLengthSubarrays([1,2]))        # Expected output: 3
print(sumOddLengthSubarrays([10,11,12]))   # Expected output: 66

Time Complexity

Try our interview co-pilot at AlgoAdvance.com