#3483
Unique 3-Digit Even Numbers
EasyArrayHash TableRecursionEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n³) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Count valid even numbers directly by fixing the last digit as even and permuting the remaining digits. This reduces unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Identify even digits from the input array.
- 2Step 2: For each even digit, fix it as the last digit and count permutations of the remaining digits ensuring no leading zeros.
- 3Step 3: Sum all valid counts for each even digit.
solution.py14 lines
1from itertools import permutations
2
3def count_even_numbers(digits):
4 from collections import Counter
5 count = 0
6 digit_count = Counter(digits)
7 for d in set(digits):
8 if d % 2 == 0:
9 digit_count[d] -= 1
10 for perm in permutations(digit_count.elements(), 2):
11 if perm[0] != 0:
12 count += 1
13 digit_count[d] += 1
14 return countℹ
Complexity note: The complexity is linear as we only traverse the digits a few times.
- 1Only even digits can be in the last position.
- 2Leading zeros are not allowed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.