Program to find sum of all odd length subarrays in Python

Given an array of positive integers, we need to find the sum of all possible odd-length subarrays. A subarray is a contiguous subsequence of the array.

For example, if the input is nums = [3,8,2,5,7], the odd-length subarrays are ?

Length 1: [3], [8], [2], [5], [7] ? sums: 3, 8, 2, 5, 7
Length 3: [3,8,2], [8,2,5], [2,5,7] ? sums: 13, 15, 14  
Length 5: [3,8,2,5,7] ? sum: 25
Total sum: 3+8+2+5+7+13+15+14+25 = 92

Approach

We iterate through all possible odd lengths (1, 3, 5, ...) and for each length, generate all subarrays of that length, then sum their elements ?

def solve(nums):
    total = 0
    
    # Generate all odd lengths from 1 to len(nums)
    odd_lengths = [i for i in range(1, len(nums) + 1) if i % 2 != 0]
    
    for length in odd_lengths:
        # For each odd length, generate all subarrays of that length
        for i in range(len(nums) - length + 1):
            total += sum(nums[i:i + length])
    
    return total

nums = [3, 8, 2, 5, 7]
result = solve(nums)
print(f"Sum of all odd-length subarrays: {result}")
Sum of all odd-length subarrays: 92

Step-by-Step Execution

Let's trace through the algorithm with our example ?

def solve_with_trace(nums):
    total = 0
    print(f"Input array: {nums}")
    
    odd_lengths = [i for i in range(1, len(nums) + 1) if i % 2 != 0]
    print(f"Odd lengths to check: {odd_lengths}")
    
    for length in odd_lengths:
        print(f"\nProcessing length {length}:")
        length_sum = 0
        
        for i in range(len(nums) - length + 1):
            subarray = nums[i:i + length]
            subarray_sum = sum(subarray)
            length_sum += subarray_sum
            print(f"  Subarray {subarray} = {subarray_sum}")
        
        print(f"  Total for length {length}: {length_sum}")
        total += length_sum
    
    return total

nums = [3, 8, 2, 5, 7]
result = solve_with_trace(nums)
print(f"\nFinal result: {result}")
Input array: [3, 8, 2, 5, 7]
Odd lengths to check: [1, 3, 5]

Processing length 1:
  Subarray [3] = 3
  Subarray [8] = 8
  Subarray [2] = 2
  Subarray [5] = 5
  Subarray [7] = 7
  Total for length 1: 25

Processing length 3:
  Subarray [3, 8, 2] = 13
  Subarray [8, 2, 5] = 15
  Subarray [2, 5, 7] = 14
  Total for length 3: 42

Processing length 5:
  Subarray [3, 8, 2, 5, 7] = 25
  Total for length 5: 25

Final result: 92

Optimized Mathematical Solution

We can solve this more efficiently by calculating how many times each element appears in odd-length subarrays ?

def optimized_solve(nums):
    total = 0
    n = len(nums)
    
    for i, num in enumerate(nums):
        # Count how many odd-length subarrays contain nums[i]
        left = i + 1      # elements to the left (including current)
        right = n - i     # elements to the right (including current)
        
        # Total subarrays containing nums[i]
        total_subarrays = left * right
        
        # Odd-length subarrays containing nums[i]
        odd_subarrays = (total_subarrays + 1) // 2
        
        total += num * odd_subarrays
    
    return total

nums = [3, 8, 2, 5, 7]
result = optimized_solve(nums)
print(f"Optimized result: {result}")
Optimized result: 92

Comparison

Approach Time Complexity Space Complexity Description
Brute Force O(n³) O(1) Generate all subarrays and sum
Mathematical O(n) O(1) Count occurrences of each element

Conclusion

The brute force approach generates all odd-length subarrays and sums them up. The optimized mathematical solution calculates how many times each element appears in odd-length subarrays, achieving O(n) time complexity.

Updated on: 2026-03-25T20:22:07+05:30

576 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements