Intuition
The array has at most 10 digits, so there are at most 10 x 9 x 8 = 720 ways to pick an ordered triple of positions; enumerate them all, keep the ones that form a valid even number with no leading zero, and use a set to drop duplicates.
Explanation
Idea
A three-digit even number is built from three positions in digits — one for the hundreds place, one for the tens place, one for the units place. A digit at a given position may be reused only if it appears multiple times in the array, so we pick three distinct indices rather than three distinct values. Because digits.length <= 10, there are at most 10 x 9 x 8 = 720 ordered index triples — small enough to try every one. Two filters decide whether a triple is valid:
- No leading zero — the hundreds digit (
digits[i]) must not be0. - Even — the units digit (
digits[k]) must be even.
The same three-digit value can be produced by different index triples (for example two copies of the digit 2), so we drop everything into a hash set and the answer is the set's size.
Walk-through with digits = [1, 2, 3, 4]
We try every ordered triple of distinct indices (i, j, k) and form 100*digits[i] + 10*digits[j] + digits[k]:
(0,1,2) -> 1,2,3 -> 123: units3is odd, reject.(0,2,1) -> 1,3,2 -> 132: hundreds1(ok), units2(even) -> add 132.(0,1,3) -> 1,2,4 -> 124: units4even -> add 124.(1,0,2) -> 2,1,3 -> 213: units3odd, reject.(1,0,3) -> 2,1,4 -> 214: even -> add 214.- ... continuing through all 24 triples whose units digit is even, we collect:
124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, 432.
That is 12 distinct values, so the answer is 12. Note 222 never appears because 2 occurs only once, and we never reuse a single index.
Why the hash set matters
For digits = [0, 2, 2] the triples (1,2,?) and (2,1,?) can form the very same number (220, 202) because the two 2s are interchangeable. The set keeps just one copy of each, giving the correct count 2.
Complexity
- Time: O(n^3) where
n = digits.length <= 10, i.e. at most ~720 constant-work iterations — effectively O(1) for the given constraints. - Space: O(k) for the hash set, where
kis the number of distinct even numbers formed (bounded by the 500 even 3-digit numbers).
Implementation
class Solution {
public int totalNumbers(int[] digits) {
Set<Integer> seen = new HashSet<>();
int n = digits.length;
for (int i = 0; i < n; i++) {
if (digits[i] == 0) continue; // no leading zeros
for (int j = 0; j < n; j++) {
if (j == i) continue;
for (int k = 0; k < n; k++) {
if (k == i || k == j) continue;
if (digits[k] % 2 != 0) continue; // units digit must be even
seen.add(digits[i] * 100 + digits[j] * 10 + digits[k]);
}
}
}
return seen.size();
}
}