Find number of subarrays with even length
Array, Iterative approach
Given an array, return sum of all subarrays with even length.
Solutions
The algorithm you provided is calculating the sum of all subarrays with even length in an array. This is done by iterating over the array and for each element, calculating the sum of all subarrays starting from that element. While calculating the sum, it checks if the length of the current subarray is even. If it is, the sum is added to the total result. This process continues for all elements in the array.
Approach - Iterative Technique
Iterates over the array and for each element, it calculates the sum of all subarrays starting from that element.
Steps
Initialization: The function
EvenLengthSubarraysSum
is defined with one parameter,arr
, which is the input array. A variableresult
is initialized to 0. This variable will hold the sum of all subarrays with even length.Outer Loop: The outer loop iterates over each element in the array with
i
as the index. For eachi
, it initializes a variablesum
toarr[i]
. This variable will hold the sum of the subarray starting from indexi
.Inner Loop: The inner loop starts from
i+1
and iterates over the rest of the array withj
as the index. For eachj
, it addsarr[j]
tosum
, effectively extending the subarray by one element.Check for Even Length: After extending the subarray, it checks if the length of the subarray is even. This is done by checking if
(i+j+1) % 2 == 0
. If the length is even, it addssum
toresult
.Return Result: After iterating over all elements and all subarrays, it returns
result
, which is the sum of all subarrays with even length.
Complexity
Time complexity:
O(N^2)
Space complexity:
O(1)
Last updated