Find number of subarrays with even sum
Array, Iterative approach
Solutions
The algorithm you provided is calculating the sum of all subarrays with even sum 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 sum 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
countEvenSum
is defined with one parameter,arr
, which is the input array. A variableresult
is initialized to 0. This variable will hold the count of subarrays with an even sum.Outer Loop: The outer loop iterates over each element in the array with
i
as the index. For eachi
, it initializes a variablesum
to 0. This variable will hold the sum of the subarray starting from indexi
.Inner Loop: The inner loop starts from
i
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 Sum: After extending the subarray, it checks if the sum of the current subarray is even. This is done by checking if
sum % 2 == 0
. If the sum is even, it incrementsresult
by 1.Return Result: After iterating over all elements and all subarrays, it returns
result
, which is the count of all subarrays with an even sum.
Complexity
Time complexity:
O(N^2)
Space complexity:
O(1)
Last updated