Problem 1295

Abstract / Summary

Count how many numbers in a list have an even number of digits.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1295.py

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        return sum(1 for n in nums if len(str(n)) % 2 == 0)
3 lines | 130 bytes | submitted October 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method findNumbers. The method receives a list of integers and returns the count of elements whose decimal representation contains an even number of digits. The logic is expressed in a concise one-liner that leverages Python’s built-in functions and a generator expression.

Core Logic

The heart of the solution is the expression passed to sum:

sum(1 for n in nums if len(str(n)) % 2 == 0)

The generator iterates over each integer n in the input list nums. For every element, the integer is converted to its string form with str(n). The len function then yields the number of characters in that string. The modulo operation % 2 determines whether the length is even. When the condition holds, the generator yields the constant 1; otherwise it yields nothing. sum aggregates all yielded 1s, producing the final count.

Step-by-Step Execution

Iteration over the Input

The generator expression implicitly creates an iterator that walks through nums. No auxiliary data structures are allocated; each element is processed on the fly.

Conversion to String

For each integer n, the call str(n) produces its decimal representation. This step handles any integer size supported by Python, including arbitrarily large values, because Python’s int type is unbounded.

Length Determination

len(str(n)) computes the number of characters in the string. For non-negative numbers this directly corresponds to the digit count. The implementation does not perform any manual digit extraction; it relies on the standard library to perform the conversion efficiently.

Evenness Check

The expression len(str(n)) % 2 == 0 evaluates to True when the digit count is even. The modulo operation is a constant-time arithmetic check.

Counting

When the evenness condition is satisfied, the generator yields 1. The surrounding sum function adds together all such 1s, resulting in the total number of even-digit integers.

Edge Cases Handled

When the input list nums is empty, the generator produces no values, and sum returns 0. This behavior correctly reflects that there are no numbers with an even digit count in an empty collection.

The conversion str(n) works for any integer, including very large values that exceed typical 32- or 64-bit limits. Because Python’s integer type can grow arbitrarily, the method remains correct for inputs of any magnitude.

Negative integers are transformed into strings that include a leading minus sign (e.g., -123). In such cases the length includes the sign character, which means the digit count is effectively offset by one. The implementation therefore treats negative numbers consistently with the string length semantics, and the result reflects the parity of the total character count.

Zero (0) is converted to the string "0" whose length is 1, an odd count, so it is not counted toward the result. This aligns with the definition of digit count for the value zero.

Performance Optimizations

The use of a generator expression inside sum avoids constructing an intermediate list of boolean flags or counts. This yields a memory-efficient solution that processes each element in a streaming fashion.

Relying on the built-in str conversion and len functions leverages highly optimized C implementations within the Python runtime, providing faster execution than a manual digit-by-digit loop written in pure Python.

By yielding a constant 1 only for qualifying numbers, the aggregation step performed by sum is reduced to a simple integer addition for each match, minimizing overhead.

Overall, the implementation balances brevity with efficient use of Python’s standard library, delivering a solution that scales well with the size of the input list while maintaining low memory consumption.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big box of numbered blocks. Some blocks have just one digit written on them and some have two or three. You want to pick out all the blocks that have an even number of digits, like ones with two, four, or six numbers painted on them.

The computer looks at every block in your box one by one. First, it turns the number on the block into a little string of digits so it can count how many there are. If the count of digits is an even number, that block goes into a special pile. Finally, it counts how many blocks ended up in that special pile to see how many successful ones were found.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.15 | σ = 1.03

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS Go Rust TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C
lkwq007 Python
lzl124631x C++
shreymehul C#
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lkwq007 Python
lzl124631x C++
shreymehul C#
suxrobGM C#
varunu28 Java
35 links | 22 authors | 10 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 easy 4 medium 1 hard
7 solutions   October 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality