Engineered
Searching Algorithms

Find Numbers with Even Number of Digits

Apply linear search to inspect and count qualifying array values.

Try It Yourself

Use the editor below to inspect every number and count how many have an even number of decimal digits. The array is unsorted, so each value must be considered.

Submit your implementation when it passes the examples. Include one-digit, multi-digit, and six-digit values.

Find Numbers with Even Number of Digits

easyLinear Search · Arrays15 minLC 1295
Problem

Given an array of positive integers, return how many values contain an even number of decimal digits.

Inspect each value and count only those with 2, 4, 6, or another even number of digits.

Example 1:

Input: nums = [12, 345, 2, 6, 7896]
Output: 2

Example 2:

Input: nums = [555, 901, 482, 1771]
Output: 1

Constraints

  • 1 ≤ nums.length ≤ 500
  • 1 ≤ nums[i] ≤ 100,000
0 attempts

Solution

Scan the array once. For each value, repeatedly remove its final decimal digit and count how many steps are needed to reach zero.

Increase the answer only when that digit count is even.

function findNumbers(nums) {
  let result = 0;

  for (const number of nums) {
    let value = number;
    let digits = 0;

    while (value > 0) {
      value = Math.floor(value / 10);
      digits++;
    }

    if (digits % 2 === 0) result++;
  }

  return result;
}

Big O notation

MeasureComplexityExplanation
TimeO(n · d)Each of n values is visited and up to d decimal digits are counted.
Auxiliary spaceO(1)Only counters for the current value and total are stored.

How is this lesson?