Unique 3-Digit Even Numbers Problem
Description
LeetCode Problem 3483.
You are given an array of digits called digits. Your task is to determine the number of distinct three-digit even numbers that can be formed using these digits.
Note: Each copy of a digit can only be used once per number, and there may not be leading zeros.
Example 1:
Input: digits = [1,2,3,4]
Output: 12
Explanation: The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.
Example 2:
Input: digits = [0,2,2]
Output: 2
Explanation: The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.
Example 3:
Input: digits = [6,6,6]
Output: 1
Explanation: Only 666 can be formed.
Example 4:
Input: digits = [1,3,5]
Output: 0
Explanation: No even 3-digit numbers can be formed.
Constraints:
3 <= digits.length <= 100 <= digits[i] <= 9
Solution
Approach: Enumerate and Deduplicate with a Set
There are at most 10 digits, so we can try every ordered choice of three different positions. Pick the position i of the last digit (it must be even), the position j of the middle digit, and the position k of the first digit (it must not be 0). Positions must be pairwise different, so a digit copy is never used twice.
Add the number 100 * digits[k] + 10 * digits[j] + digits[i] to a set. Equal numbers built from different copies of a digit collapse into one entry, and the answer is the size of the set.
Complexity: O(n3) time and O(n3) space for the set, where n is the length of digits (at most 10, so at most 720 candidates).
class Solution:
def totalNumbers(self, digits: List[int]) -> int:
s = set()
for i, a in enumerate(digits):
if a & 1:
continue
for j, b in enumerate(digits):
if i == j:
continue
for k, c in enumerate(digits):
if c == 0 or k in (i, j):
continue
s.add(c * 100 + b * 10 + a)
return len(s)