04. Count Even Numbers in an Array

Difficulty:EasyPattern:CountingTime:O(n)Space:O(1)

Determine the count of even numbers contained in an array.

How It Works & Algorithmic Design

This combines Conditional Filtering with Counter Incrementation:

  1. Divisibility Condition: A integer $x$ is defined as even if $x \pmod 2 = 0$.
  2. Counter Setup: Initialize count = 0.
  3. Evaluation Loop: Traverse through each number in the array. Apply the modulo operator (value % 2). If the remainder equals 0, increment count by 1.
  4. Negative Numbers: The condition value % 2 === 0 holds 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: 3
There 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.