Find Numbers with Even Number of Digits — LeetCode #1295 (Easy)
Tags: Array, Math
Related patterns: Array, String Manipulation
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
The brute force approach involves checking each number in the array individually to count its digits. For each number, we can repeatedly divide it by 10 until it becomes 0, counting how many times we divide to determine the number of digits.
The time complexity is O(n²) because for each number (n), we may have to count its digits, which can take up to O(log m) time, where m is the maximum number in the array. However, since the maximum number of digits is limited, we can consider it constant for practical purposes.
- Step 1: Initialize a counter to zero.
- Step 2: For each number in the array, initialize a digit count to zero.
- Step 3: While the number is greater than 0, divide the number by 10 and increment the digit count.
- Step 4: After counting digits, check if the count is even. If it is, increment the counter.
- Step 5: Return the counter after processing all numbers.
Input: nums = [12, 345, 2, 6, 7896]
1. Initialize count = 0.
2. Check 12: digit count = 2 (even), count = 1.
3. Check 345: digit count = 3 (odd), count remains 1.
4. Check 2: digit count = 1 (odd), count remains 1.
5. Check 6: digit count = 1 (odd), count remains 1.
6. Check 7896: digit count = 4 (even), count = 2.
Final count = 2.
Optimal Solution approach
Time complexity: O(n). Space complexity: 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.
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).
- Step 1: Initialize a counter to zero.
- Step 2: For each number in the array, convert the number to a string.
- Step 3: Check the length of the string. If the length is even, increment the counter.
- Step 4: Return the counter after processing all numbers.
Input: nums = [12, 345, 2, 6, 7896]
1. Initialize count = 0.
2. Check 12: length = 2 (even), count = 1.
3. Check 345: length = 3 (odd), count remains 1.
4. Check 2: length = 1 (odd), count remains 1.
5. Check 6: length = 1 (odd), count remains 1.
6. Check 7896: length = 4 (even), count = 2.
Final count = 2.
Key Insights
- Counting digits can be done using division or string conversion.
- Evenness can be checked using the modulus operator.
Common Mistakes
- Not considering single-digit numbers as having odd digits.
- Overcomplicating the digit counting process.
Interview Tips
- Always clarify the constraints and edge cases before coding.
- Think about both time and space complexity when discussing solutions.
- Practice explaining your thought process clearly while coding.