04. Count Even Numbers in an Array
Determine the count of even numbers contained in an array.
How It Works & Algorithmic Design
This combines Conditional Filtering with Counter Incrementation:
- Divisibility Condition: A integer $x$ is defined as even if $x \pmod 2 = 0$.
- Counter Setup: Initialize
count = 0. - Evaluation Loop: Traverse through each number in the array. Apply the modulo operator (
value % 2). If the remainder equals0, incrementcountby 1. - Negative Numbers: The condition
value % 2 === 0holds true for negative even integers as well (e.g.,-4 % 2 === 0), making this approach robust across integer domains.
Why This Approach Works Best
It processes the input in $O(n)$ runtime and $O(1)$ extra space without creating intermediate filtered arrays in memory.
Example Walkthrough
Input:
[1, 4, 7, 8, 10, 13]Mixed odd and even integers.
Evaluation Trace:
1 (Odd) -> 4 (Even, count=1) -> 7 (Odd) -> 8 (Even, count=2) -> 10 (Even, count=3) -> 13 (Odd)Only increments counter when number % 2 == 0.
Output:
3There are three even numbers (4, 8, 10).
Answer: Count even values
function countEven(arr) {
let count = 0;
for (const value of arr) {
if (value % 2 === 0) count++;
}
return count;
}💡 Filter numbers using modulo 2 and increment a counter variable.
Key Takeaways
- Modulo operator (
%) accurately checks for divisibility. - Avoid instantiating auxiliary filtered arrays to keep space complexity at $O(1)$.
- Modulo operation works consistently for both positive and negative even integers.