1295. Find Numbers with Even Number of Digits
Problem Description
You are given an array nums
containing integers. Your task is to count how many numbers in this array have an even number of digits.
For example:
- The number
12
has 2 digits (even count) - The number
345
has 3 digits (odd count) - The number
2
has 1 digit (odd count) - The number
6789
has 4 digits (even count)
The solution works by converting each number to a string to easily count its digits. For each number x
in the array, len(str(x))
gives us the digit count. We then check if this count is even using the modulo operator (% 2 == 0
). The sum()
function counts how many numbers satisfy this condition, giving us the final answer.
Intuition
The key insight is that we need to count the digits in each number. While we could count digits mathematically (by repeatedly dividing by 10), the simplest approach is to convert each number to a string since the length of the string representation directly gives us the digit count.
Once we know how to get the digit count, checking if it's even is straightforward - we just need to verify if the count is divisible by 2. In Python, we can check this using count % 2 == 0
.
Since we're counting how many numbers satisfy a condition, we can use Python's generator expression with sum()
. This works because True
evaluates to 1
and False
evaluates to 0
in Python. So sum(condition for x in nums)
effectively counts how many times the condition is true.
The one-liner solution sum(len(str(x)) % 2 == 0 for x in nums)
elegantly combines all these ideas: convert to string, check digit count parity, and count the matches all in a single expression.
Learn more about Math patterns.
Solution Approach
We traverse each element x
in the array nums
. For the current element x
, we directly convert it to a string and then check if its length is even. If it is, we increment the answer by one.
The implementation follows these steps:
-
Iterate through the array: We go through each number
x
innums
-
Convert to string: For each number
x
, we usestr(x)
to convert it to its string representation -
Count digits: We use
len(str(x))
to get the number of digits in the number -
Check if even: We check if the digit count is even using the condition
len(str(x)) % 2 == 0
-
Count matches: We use Python's
sum()
function with a generator expression to count how many numbers have an even digit count
The complete solution becomes a single line: sum(len(str(x)) % 2 == 0 for x in nums)
This approach has a time complexity of O(n × d) where n is the number of elements in the array and d is the average number of digits in the numbers (since string conversion takes O(d) time). The space complexity is O(d) for the temporary string created during conversion.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a concrete example with the array nums = [12, 345, 2, 6789, 100]
.
We'll process each number and check if it has an even number of digits:
-
First number: 12
- Convert to string:
"12"
- Count digits:
len("12") = 2
- Check if even:
2 % 2 == 0
→True
- Running count: 1
- Convert to string:
-
Second number: 345
- Convert to string:
"345"
- Count digits:
len("345") = 3
- Check if even:
3 % 2 == 0
→False
- Running count: 1 (no change)
- Convert to string:
-
Third number: 2
- Convert to string:
"2"
- Count digits:
len("2") = 1
- Check if even:
1 % 2 == 0
→False
- Running count: 1 (no change)
- Convert to string:
-
Fourth number: 6789
- Convert to string:
"6789"
- Count digits:
len("6789") = 4
- Check if even:
4 % 2 == 0
→True
- Running count: 2
- Convert to string:
-
Fifth number: 100
- Convert to string:
"100"
- Count digits:
len("100") = 3
- Check if even:
3 % 2 == 0
→False
- Running count: 2 (no change)
- Convert to string:
Final answer: 2 (the numbers 12 and 6789 have an even number of digits)
Using the one-liner solution: sum(len(str(x)) % 2 == 0 for x in nums)
produces:
- For x=12:
len(str(12)) % 2 == 0
→True
(contributes 1) - For x=345:
len(str(345)) % 2 == 0
→False
(contributes 0) - For x=2:
len(str(2)) % 2 == 0
→False
(contributes 0) - For x=6789:
len(str(6789)) % 2 == 0
→True
(contributes 1) - For x=100:
len(str(100)) % 2 == 0
→False
(contributes 0) - Sum: 1 + 0 + 0 + 1 + 0 = 2
Solution Implementation
1class Solution:
2 def findNumbers(self, nums: List[int]) -> int:
3 """
4 Count how many numbers in the array have an even number of digits.
5
6 Args:
7 nums: List of integers to check
8
9 Returns:
10 Count of numbers with even digit count
11 """
12 # Convert each number to string, check if digit count is even, sum the True values
13 return sum(len(str(num)) % 2 == 0 for num in nums)
14
1class Solution {
2 /**
3 * Finds the count of numbers that contain an even number of digits
4 * @param nums - input array of integers
5 * @return count of numbers with even number of digits
6 */
7 public int findNumbers(int[] nums) {
8 // Initialize counter for numbers with even digit count
9 int evenDigitCount = 0;
10
11 // Iterate through each number in the array
12 for (int number : nums) {
13 // Convert number to string and check if digit count is even
14 if (String.valueOf(number).length() % 2 == 0) {
15 // Increment counter if number has even number of digits
16 evenDigitCount++;
17 }
18 }
19
20 // Return the total count of numbers with even digits
21 return evenDigitCount;
22 }
23}
24
1class Solution {
2public:
3 int findNumbers(vector<int>& nums) {
4 int evenDigitCount = 0; // Counter for numbers with even number of digits
5
6 // Iterate through each number in the array
7 for (int& num : nums) {
8 // Convert number to string and check if digit count is even
9 // If even, increment the counter (adding 1 if true, 0 if false)
10 evenDigitCount += (to_string(num).size() % 2 == 0);
11 }
12
13 return evenDigitCount; // Return total count of numbers with even digits
14 }
15};
16
1/**
2 * Finds the count of numbers in the array that have an even number of digits
3 * @param nums - Array of integers to check
4 * @returns The count of numbers with even digit count
5 */
6function findNumbers(nums: number[]): number {
7 // Filter the array to keep only numbers with even digit count, then return the length
8 return nums.filter((num: number) => {
9 // Convert number to string to count digits
10 const digitCount: number = num.toString().length;
11 // Check if digit count is even
12 return digitCount % 2 === 0;
13 }).length;
14}
15
Time and Space Complexity
The time complexity is O(n × log M)
, where n
is the length of the array nums
and M
is the maximum value of the elements in the array.
- The code iterates through each element in
nums
once, contributingO(n)
to the complexity - For each element
x
, converting it to a string usingstr(x)
takesO(log₁₀ x)
time, which is proportional to the number of digits inx
- In the worst case, the largest element has value
M
, requiringO(log M)
time for conversion - The
len()
operation on the string isO(1)
after string conversion - Therefore, the overall time complexity is
O(n × log M)
The space complexity is O(log M)
.
- The generator expression itself uses
O(1)
space as it processes elements one at a time - However, for each element
x
, thestr(x)
conversion creates a temporary string whose length is proportional to the number of digits inx
- The largest temporary string created would be for the maximum value
M
, which requiresO(log M)
space - Since only one string is created at a time (not stored permanently), the space complexity is
O(log M)
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Handling Negative Numbers
The current solution doesn't account for negative numbers correctly. When converting a negative number to a string, the minus sign is included in the length count, which can lead to incorrect results.
Example Issue:
-12
converts to"-12"
with length 3 (odd), but the actual digit count should be 2 (even)-999
converts to"-999"
with length 4 (even), but the actual digit count should be 3 (odd)
Solution: Use the absolute value before converting to string:
return sum(len(str(abs(num))) % 2 == 0 for num in nums)
2. Mathematical Approach vs String Conversion
While string conversion is intuitive and readable, it involves type conversion overhead. For performance-critical applications with large datasets, a mathematical approach might be more efficient.
Alternative Mathematical Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for num in nums:
num = abs(num) # Handle negative numbers
digits = 0
while num > 0:
digits += 1
num //= 10
if digits % 2 == 0:
count += 1
return count
Or using logarithms:
import math
def findNumbers(self, nums: List[int]) -> int:
count = 0
for num in nums:
if num == 0:
digits = 1
else:
digits = math.floor(math.log10(abs(num))) + 1
if digits % 2 == 0:
count += 1
return count
3. Edge Case: Zero
The number 0
has 1 digit, which the current solution handles correctly. However, in the mathematical logarithm approach, log10(0)
is undefined, requiring special handling as shown above.
4. Memory Consideration
Although the string conversion approach has O(d) space complexity per conversion, creating many temporary strings in a tight loop could cause unnecessary garbage collection pressure in memory-constrained environments. The mathematical approach avoids this by working directly with integers.
How does quick sort divide the problem into subproblems?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!