#2094

Finding 3-Digit Even Numbers

Easy
ArrayHash TableRecursionSortingEnumerationHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal approach focuses on identifying the even digits first and then constructing valid 3-digit numbers without leading zeros. This reduces unnecessary checks and ensures we only consider valid combinations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the occurrences of each digit using a frequency array.
  2. 2Step 2: Identify even digits and iterate through them as potential last digits of the 3-digit number.
  3. 3Step 3: For each even digit, form combinations with the remaining digits, ensuring no leading zeros.
solution.py17 lines
1from collections import Counter
2
3def findEvenNumbers(digits):
4    count = Counter(digits)
5    result = set()
6    for last_digit in [d for d in count if d % 2 == 0]:
7        count[last_digit] -= 1
8        for first_digit in count:
9            if first_digit == 0 and count[first_digit] == 0:
10                continue
11            for second_digit in count:
12                if count[first_digit] > 0 and count[second_digit] > 0:
13                    num = first_digit * 100 + second_digit * 10 + last_digit
14                    if num >= 100:
15                        result.add(num)
16        count[last_digit] += 1
17    return sorted(result)

Complexity note: The time complexity is O(n) as we only iterate through the digits a limited number of times. The space complexity is O(n) due to the storage of unique numbers.

  • 1Even numbers must end with an even digit (0, 2, 4, 6, 8).
  • 2Leading zeros are not allowed, so the first digit must be non-zero.

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