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: There are 3 even numbers (2, 4, 6)
Example 2: No even numbers in [1, 3, 5]
Example 3: All 4 numbers are even
Algorithm Flow
Solution Approach
Iterate through the array and classify each element as even or odd using the modulo operator.
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
class Solution {
public int count_even(int[] nums) {
int count = 0;
for (int num : nums) {
if (num % 2 == 0) count++;
}
return count;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
