Skip to content

2094. Finding 3-Digit Even Numbers

  • Time: $O(10^3) = O(1)$
  • Space: $O(10 + |\texttt{digits}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  vector<int> findEvenNumbers(vector<int>& digits) {
    vector<int> ans;
    vector<int> count(10);

    for (const int digit : digits)
      ++count[digit];

    // Try to construct `abc`.
    for (int a = 1; a <= 9; ++a)
      for (int b = 0; b <= 9; ++b)
        for (int c = 0; c <= 8; c += 2)
          if (count[a] > 0 && count[b] > (b == a) &&
              count[c] > (c == a) + (c == b))
            ans.push_back(a * 100 + b * 10 + c);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int[] findEvenNumbers(int[] digits) {
    List<Integer> ans = new ArrayList<>();
    int[] count = new int[10];

    for (final int digit : digits)
      ++count[digit];

    // Try to construct `abc`.
    for (int a = 1; a <= 9; ++a)
      for (int b = 0; b <= 9; ++b)
        for (int c = 0; c <= 8; c += 2)
          if (count[a] > 0 && count[b] > (b == a ? 1 : 0) &&
              count[c] > (c == a ? 1 : 0) + (c == b ? 1 : 0))
            ans.add(a * 100 + b * 10 + c);

    return ans.stream().mapToInt(Integer::intValue).toArray();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def findEvenNumbers(self, digits: list[int]) -> list[int]:
    ans = []
    count = collections.Counter(digits)

    # Try to construct `abc`.
    for a in range(1, 10):
      for b in range(0, 10):
        for c in range(0, 9, 2):
          if count[a] > 0 and count[b] > (
                  b == a) and count[c] > (
                  c == a) + (
                  c == b):
            ans.append(a * 100 + b * 10 + c)

    return ans