#1295

Find Numbers with Even Number of Digits

Easy
ArrayMathArrayString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the fact that we can convert each number to a string and directly check the length of the string to determine the number of digits. This is efficient and straightforward, allowing us to avoid the repeated division.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: For each number in the array, convert the number to a string.
  3. 3Step 3: Check the length of the string. If the length is even, increment the counter.
  4. 4Step 4: Return the counter after processing all numbers.
solution.py4 lines
1# Full working Python code
2
3def count_even_digit_numbers(nums):
4    return sum(1 for num in nums if len(str(num)) % 2 == 0)

Complexity note: The time complexity is O(n) because we only iterate through the array once, and checking the string length is O(1) since the maximum length is constant (at most 6 for the given constraints).

  • 1Counting digits can be done using division or string conversion.
  • 2Evenness can be checked using the modulus operator.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.