Code Logo

Even Count

Published at10 Jan 2026
1D Array Easy 13 views
Like1

Given an array of integers, count how many elements are even and how many are odd. Return the result as two numbers: the even count followed by the odd count.

For example, in [2, 3, 4, 5, 6], there are 3 evens (2, 4, 6) and 2 odds (3, 5). In [1, 3, 5], there are 0 evens and 3 odds. An empty array returns (0, 0).

Counting even and odd numbers teaches the modulo operator (%) for parity classification. A number is even if n % 2 == 0, meaning it is divisible by 2 with no remainder.

The solution iterates through the array, checks each element for evenness, and increments the appropriate counter. This runs in O(n) time with O(1) space.

Edge cases include an empty array (0, 0), all even numbers, all odd numbers, and negative numbers (negative evens also satisfy n % 2 == 0).

Example Input & Output

Example 1
Input
nums = [1, 2, 3, 4, 5, 6]
Output
3
Explanation

Example 1: There are 3 even numbers (2, 4, 6)

Example 2
Input
nums = [1, 3, 5]
Output
0
Explanation

Example 2: No even numbers in [1, 3, 5]

Example 3
Input
nums = [2, 4, 6, 8]
Output
4
Explanation

Example 3: All 4 numbers are even

Algorithm Flow

Recommendation Algorithm Flow for Even Count

Solution Approach

Iterate through the array and classify each element as even or odd using the modulo operator.

function evenOddCount(arr)
  even = 0, odd = 0
  for i = 0 to length(arr) - 1
    if arr[i] % 2 == 0 then even = even + 1
    else odd = odd + 1
  return (even, odd)

Initialize both counters to 0. Loop through each element. If arr[i] % 2 == 0, increment the even counter. Otherwise, increment the odd counter. Return both counts.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int count_even(int[] nums) {
        int count = 0;
        for (int num : nums) {
            if (num % 2 == 0) count++;
        }
        return count;
    }
}