AlgoMaster Logo

Count Even and Odd Numbers

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

Split the array into even and odd values and report how many landed in each. The counting is straightforward: look at every element, decide its parity, and increment the right counter. The detail that needs care is the parity test itself, especially for negative numbers.

The modulo operator checks parity: x % 2 is the remainder after dividing by 2. For negative operands, the sign of that remainder varies across languages. A negative odd number like -3 gives -1 for x % 2 in Java, C++, C#, Go, and Rust, not 1, so a test like x % 2 == 1 would wrongly classify -3 as not odd. The even test x % 2 == 0 avoids this, because the remainder is 0 for every even number whether positive or negative. So the branch is built around the even check.

A single pass through the array settles the problem, with no sorting or extra data structure.

Key Constraints:

  • -2^31 <= nums[i] <= 2^31 - 1 → Values can be negative. In Java, C++, C#, Go, and Rust, x % 2 returns -1 for a negative odd number rather than 1, so testing x % 2 == 1 for odd would miss negative odds. Test x % 2 == 0 for even instead, which is 0 for every even number regardless of sign, and treat everything else as odd.
  • 0 is even → Zero divides by 2 with no remainder, so 0 % 2 == 0 and it counts toward evenCount.
  • 0 <= nums.length → The array may be empty. With no elements to scan, both counters stay at their initial value of 0, so the answer is [0, 0].

Approach 1: Linear Scan with Modulo

Intuition

Keep two counters, evenCount and oddCount, both starting at 0. Walk the array once, run one parity test per element, and increment the matching counter.

Branch on x % 2 == 0. When true, the value is even, so increment evenCount. Otherwise increment oddCount. Using the even check keeps the logic correct for negatives, whose odd remainder may be 1 or -1 depending on the language.

Algorithm

  1. Set evenCount = 0 and oddCount = 0.
  2. Loop over every element x in nums.
  3. If x % 2 == 0, increment evenCount. Otherwise, increment oddCount.
  4. After the loop, return [evenCount, oddCount].

Example Walkthrough

Input:

0
-3
1
-2
2
0
nums

Start with evenCount = 0 and oddCount = 0. The first value is -3. Here -3 % 2 is -1, which is not 0, so -3 is odd and oddCount becomes 1. The second value is -2. Here -2 % 2 is 0, so -2 is even and evenCount becomes 1. The third value is 0. Here 0 % 2 is 0, so 0 is even and evenCount becomes 2. The scan ends with evenCount = 2 and oddCount = 1.

Note how testing for == 0 correctly classifies -3 as odd, where a test of -3 % 2 == 1 would have failed because the remainder is -1.

0
2
1
1
result

Code