Sum Of All Odd Length Subarrays

Solution For Sum Of All Odd Length Subarrays

Problem Statement:

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:

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 the sums together, we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

Solution:

The problem can be solved by following the given steps:
1. Initialize a variable ‘sum’ to 0.
2. Traverse the input array ‘arr’ using two nested loops. The outer loop will iterate over all possible subarrays of ‘arr’, and the inner loop will iterate over all elements within the subarray.
3. For each subarray, check if its length is odd.
4. If the length of the subarray is odd, calculate its sum and add it to the ‘sum’ variable.
5. Return the ‘sum’ variable as the final result.

Implementation:

Here is the Python implementation of the above approach:

def sumOddLengthSubarrays(arr):
# Initialize the sum variable to 0
sum = 0
# Traverse the input array using two nested loops
for i in range(len(arr)):
for j in range(i, len(arr)):
# Check if the length of the subarray is odd
if (j – i + 1) % 2 == 1:
# Calculate the sum of the current subarray
for k in range(i, j+1):
sum += arr[k] # Return the final sum
return sum

Test the solution with the given example

arr = [1,4,2,5,3] print(sumOddLengthSubarrays(arr)) # Output: 58

Time and Space Complexity:

Time Complexity: The time complexity of the above algorithm is O(n^3), where ‘n’ is the length of the input array. This is because we are traversing the input array using two nested loops, and for each subarray, we are calculating its sum in an additional loop.

Space Complexity: The space complexity of the above algorithm is O(1), as we are not using any extra space to solve the problem, except for the ‘sum’ variable.

Step by Step Implementation For Sum Of All Odd Length Subarrays

class Solution {
    public int sumOddLengthSubarrays(int[] arr) {
        //edge case
        if(arr == null || arr.length == 0)
            return 0;
        
        int sum = 0;
        
        //for each index, we will find the sum of all odd length subarrays that start with that index
        for(int i = 0; i < arr.length; i++){
            //odd length subarrays that start with i have (i+1) * (arr.length-i) subarrays
            int length = (i+1) * (arr.length-i);
            
            //if length is odd, we can just add arr[i] to the sum
            if(length % 2 == 1)
                sum += arr[i];
            
            //if length is even, we need to find the middle element to add to the sum
            else{
                int middle = length / 2;
                sum += arr[i] + arr[i+middle];
            }
        }
        
        return sum;
    }
}
def sumOddLengthSubarrays(arr): 
    
    # Initialize result 
    res = 0
  
    # Consider all possible subarrays 
    # of arr[] and calculate sum 
    # of odd length subarrays 
    for i in range(len(arr)): 
        for j in range(i, len(arr)): 
              
            # Calculate sum of current subarray 
            curr_sum = 0
            for k in range(i, j + 1): 
                curr_sum += arr[k] 
  
            # Add 'curr_sum' if it is odd 
            if ((j - i) % 2 != 0): 
                res += curr_sum 
  
    # return answer 
    return res
/**
 * @param {number[]} arr
 * @return {number}
 */
 
// We can solve this problem in O(n) time using a prefix sum array. 
// The idea is as follows: for each element at index i, 
// we find the number of subarrays that start and end at index i 
// (these are the subarrays of odd length with the element at index i as the maximum element). 
// We can find the number of such subarrays in O(1) time 
// by using the following formula (n is the length of the array):
 
// Number of subarrays = ((i + 1) * (n - i))
 
// We add the number of subarrays for each element to find the final sum.
 
var sumOddLengthSubarrays = function(arr) {
    let prefixSum = new Array(arr.length).fill(0);
    let sum = 0;
    
    // Fill prefixSum array. 
    // prefixSum[i] will store the sum of elements from index 0 to i-1.
    for(let i = 0; i < arr.length; i++) {
        if(i === 0) {
            prefixSum[i] = arr[i];
        } else {
            prefixSum[i] = prefixSum[i-1] + arr[i];
        }
    }
    
    // For each element at index i, 
    // find the number of subarrays that start and end at index i 
    // and add it to the sum.
    for(let i = 0; i < arr.length; i++) {
        let numSubarrays = ((i + 1) * (arr.length - i));
        sum += numSubarrays * arr[i];
    }
    
    // Subtract the sum of elements that are part of even length subarrays.
    for(let i = 1; i < arr.length - 1; i++) {
        let left = 0;
        let right = arr.length - 1;
        
        // Find the number of subarrays with even length that include arr[i].
        while(left < i && right > i) {
            let numSubarrays = ((left + 1) * (right - left));
            sum -= numSubarrays * arr[i];
            left++;
            right--;
        }
    }
    
    return sum;
};
int sumOddLengthSubarrays(vector& arr) {
        int n = arr.size(), sum = 0;
        for (int i = 0; i < n; ++i) {
            sum += ((i + 1) * (n - i) + 1) / 2 * arr[i]; // calculate the number of subarrays with arr[i] as the median element
        }
        return sum;
    }
public class Solution {
    public int SumOddLengthSubarrays(int[] arr) {
        // Create an empty hash set 
        HashSet hset = new HashSet(); 
  
        // Iterate through the array 
        for (int i = 0; i < arr.Length; i++) { 
  
            // If element is not present, then insert it 
            if (!hset.Contains(arr[i])) { 
                hset.Add(arr[i]); 
            } 
        } 
  
        // Return the count of distinct elements 
        return hset.Count; 
    } 
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]