Coding problem · Easy · Basics

Count the Even Numbers

Easy Algorithms & data structures

Return how many numbers in nums are even (divisible by 2). Negative numbers and zero count too.

Example 1

Input: nums = [1,2,3,4,6]
Output: 3

Example 2

Input: nums = [1,3,5]
Output: 0

Hints

Hint 1

A number is even when n % 2 === 0.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Loop and count elements where n % 2 == 0. In some languages -3 % 2 is -1, so compare with 0 rather than checking for 1.

Reference solution

function countEvens(nums) {
  return nums.filter((n) => n % 2 === 0).length;
}

Was this page helpful?