Count Even and Odd Numbers in an Array

Solve this Problem
Easy5 min
Topics
Companies
Given an array nums, return [evens, odds]: how many elements are even and how many are odd. Counting by category is the accumulator pattern with more than one counter. Because every integer is either even or oddComplementary CategoriesTwo groups that together cover everything with no overlap, so knowing one count gives the other., the second count can also be derived from the first — a small example of using a fact about the data to do less work.

Test Case 1:

Input:nums = [4, 7, 10, 3, 0]
Output:[3, 2]
Explanation:4, 10 and 0 are even; 7 and 3 are odd.

Test Case 2:

Input:nums = [-5, -2]
Output:[1, 1]
Explanation:Negative numbers are even or odd in the same way.

Constraints

  • ◆1 ≤ nums.length ≤ 1000
  • ◆-1000000 ≤ nums[i] ≤ 1000000

Try the Dry Run

Approach & Solutions

Check Each NumberGood

Keep two counters. For every element, test value % 2 == 0: if true, add one to the even counter, otherwise to the odd counter. Return [evens, odds].

TimeO(n)
SpaceO(1)
class Solution { public int[] countEvenOdd(int[] nums) { int evens = 0; int odds = 0; for (int value : nums) { if (value % 2 == 0) { evens++; } else { odds++; } } return new int[] {evens, odds}; } }
Count Evens, Derive OddsOptimal

Every integer is either even or odd, never both. So count only the evens; the odds are whatever is left: length − evens. One counter and one subtraction replace the second branch.

TimeO(n)
SpaceO(1)
class Solution { public int[] countEvenOdd(int[] nums) { int evens = 0; for (int value : nums) { if (value % 2 == 0) { evens++; } } int odds = nums.length - evens; return new int[] {evens, odds}; } }

Related Problems