3483. Unique 3-Digit Even Numbers
Problem Description
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.
Intuition
To solve this problem, the main idea is to systematically create all possible three-digit even numbers by using the digits provided. An even number must end with an even digit. Therefore, our first step would be to identify digits that can be used as the last digit of our number.
Here's how the solution progresses:
-
Use a set: Utilize a set to store numbers to ensure all numbers are distinct, as sets automatically manage duplicates.
-
Iteration Strategy:
- First, loop through each digit to decide which can be the last digit, ensuring it is even. This will greatly reduce potential candidates.
- For each even digit picked as the ending digit, choose two more digits out of the remaining to construct the hundreds and tens place.
- Ensure no digit is repeated within any number, i.e., keep track of indices used when forming a number to avoid using the same digit more than once.
-
Avoid Leading Zero: When forming the number, ensure the hundreds place (first digit) is not zero, which disqualifies it from being a valid three-digit number.
By following this organized and methodical way of generating numbers while using a set to filter out duplicates, we efficiently find all valid combinations.
Learn more about Recursion patterns.
Solution Approach
The solution implements a method to systematically create all potential three-digit even numbers from the given digits
list. This approach efficiently ensures that only valid and distinct numbers are counted. Hereβs a detailed breakdown of the solution:
-
Hash Set Usage:
- We employ a hash set
s
to store the numbers we generate. The purpose of using a set is to automatically handle duplicates, meaning only unique numbers are recorded.
- We employ a hash set
-
Enumeration of Digits:
- Iterate over each digit in the
digits
list to determine which can be the last digit of the number. For a number to be even, it needs to end in an even digit (0, 2, 4, 6, 8). This serves as our starting point for constructing a number.
- Iterate over each digit in the
-
Nested Loops for Number Construction:
- For each possible last digit
a
(must be even), utilize two more loops to select different digits for the hundreds and tens places. The constraints include not reusing any digit that serves as the last digit while choosing the middle and first digits. - Specifically:
- The first loop selects the digit
b
for the tens place. - The second loop chooses the digit
c
for the hundreds place.
- The first loop selects the digit
- For each possible last digit
-
Ensure Valid Three-Digit Number:
- We ensure that the three-digit number does not start with zero (
c
should not be zero), thereby disallowing invalid numbers like012
. - If these conditions are met, form the number using the formula
c * 100 + b * 10 + a
and insert it into the set.
- We ensure that the three-digit number does not start with zero (
-
Result:
- The size of the set (
len(s)
) gives the total count of distinct three-digit even numbers that can be formed as desired.
- The size of the set (
This approach is clear and concise, leveraging the set
for uniqueness constraint and nested loops for systematic enumeration, all while adhering to number formation rules.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through an example using the solution approach to better understand how it works.
Suppose you are given the array of digits: [1, 2, 3, 4]
.
-
Set Up the Hash Set: Initialize an empty set
s
to store distinct three-digit even numbers. -
Identify Even Digits for the Last Position:
- The potential even digits from our list for the last digit are
2
and4
.
- The potential even digits from our list for the last digit are
-
Construct Numbers Using Nested Loops:
-
Choose
2
as the last digit:- Try
3
as the tens digit and1
as the hundreds digit. Form the number132
, which is valid, and add it to the set. - Try
1
as the tens digit and3
as the hundreds digit. Form the number312
, which is valid, and add it to the set. - Other combinations include
312
and132
again, but they would already exist in the set.
- Try
-
Choose
4
as the last digit:- Try
3
as the tens digit and1
as the hundreds digit. Form the number134
, which is valid, and add it to the set. - Try
1
as the tens digit and3
as the hundreds digit. Form the number314
, which is valid, and add it to the set. - Any other permutations that result in the same number are naturally ignored due to the set's mechanics.
- Try
-
-
Result Calculation:
- The set by now contains the numbers:
132
,312
,134
,314
. - The total number of distinct three-digit even numbers is given by
len(s)
, resulting in4
.
- The set by now contains the numbers:
This walkthrough demonstrates how the problem is tackled with a systematic approach using sets and nested loops to achieve the desired distinct outcomes.
Solution Implementation
1from typing import List
2
3class Solution:
4 def totalNumbers(self, digits: List[int]) -> int:
5 unique_numbers = set()
6
7 # Iterate over each digit considering it as a possible unit place digit
8 for i, unit_digit in enumerate(digits):
9 if unit_digit % 2 != 0:
10 # Skip if the unit digit is odd
11 continue
12
13 # Iterate over each digit for the possible tens place digit
14 for j, tens_digit in enumerate(digits):
15 if i == j:
16 # Skip if it's the same digit as the unit place
17 continue
18
19 # Iterate over each digit for the possible hundreds place digit
20 for k, hundreds_digit in enumerate(digits):
21 if hundreds_digit == 0 or k in (i, j):
22 # Skip if the hundreds digit is 0 or if it's the same as unit or tens place
23 continue
24
25 # Create the unique three-digit number and add to the set
26 unique_number = hundreds_digit * 100 + tens_digit * 10 + unit_digit
27 unique_numbers.add(unique_number)
28
29 # Return the count of unique numbers stored in set
30 return len(unique_numbers)
31
1import java.util.HashSet;
2import java.util.Set;
3
4class Solution {
5
6 public int totalNumbers(int[] digits) {
7 Set<Integer> uniqueNumbers = new HashSet<>(); // Set to store distinct numbers
8 int numDigits = digits.length; // Store the length of the digits array
9
10 for (int i = 0; i < numDigits; ++i) {
11 // Skip if the current digit is odd, as we want 3-digit numbers ending in an even digit
12 if (digits[i] % 2 == 1) {
13 continue;
14 }
15
16 for (int j = 0; j < numDigits; ++j) {
17 // Ensure the second digit isn't the same as the last digit
18 if (i == j) {
19 continue;
20 }
21
22 for (int k = 0; k < numDigits; ++k) {
23 // Ensure the first digit isn't 0 (leading zeroes are not allowed),
24 // and that it's different from the other selected digits
25 if (digits[k] == 0 || k == i || k == j) {
26 continue;
27 }
28
29 // Form the number by placing digits in hundreds, tens, and units positions
30 int number = digits[k] * 100 + digits[j] * 10 + digits[i];
31 uniqueNumbers.add(number); // Add the number to the set
32 }
33 }
34 }
35
36 return uniqueNumbers.size(); // Return the count of unique 3-digit numbers
37 }
38}
39
1#include <vector>
2#include <unordered_set>
3
4class Solution {
5public:
6 // Method to find the total number of distinct three-digit numbers
7 // that can be formed using the given vector of digits.
8 int totalNumbers(std::vector<int>& digits) {
9 std::unordered_set<int> unique_numbers; // Set to store unique numbers
10 int count = digits.size();
11
12 for (int i = 0; i < count; ++i) {
13 // Check if the digit at position i is odd
14 // The last digit in a three-digit number must be even
15 if (digits[i] % 2 == 1) {
16 continue;
17 }
18 for (int j = 0; j < count; ++j) {
19 // Skip if indices i and j are the same
20 if (i == j) {
21 continue;
22 }
23 for (int k = 0; k < count; ++k) {
24 // Ensure the number is valid by checking:
25 // The first digit cannot be 0, and indices must be different
26 if (digits[k] == 0 || k == i || k == j) {
27 continue;
28 }
29 // Construct a three-digit number and add it to the set
30 int number = digits[k] * 100 + digits[j] * 10 + digits[i];
31 unique_numbers.insert(number);
32 }
33 }
34 }
35
36 // Return the size of the set which represents the count of unique numbers
37 return unique_numbers.size();
38 }
39};
40
1function totalNumbers(digits: number[]): number {
2 // Set to store unique three-digit numbers
3 const uniqueNumbers = new Set<number>();
4 const numberOfDigits = digits.length;
5
6 // Iterate through each digit to use as the least significant digit (unit place)
7 for (let unitPlaceIndex = 0; unitPlaceIndex < numberOfDigits; ++unitPlaceIndex) {
8 // Skip if the digit is odd since we want even numbers
9 if (digits[unitPlaceIndex] % 2 === 1) {
10 continue;
11 }
12
13 // Iterate through each digit for the tens place
14 for (let tensPlaceIndex = 0; tensPlaceIndex < numberOfDigits; ++tensPlaceIndex) {
15 // Skip if the index of tens place and unit place are the same
16 if (unitPlaceIndex === tensPlaceIndex) {
17 continue;
18 }
19
20 // Iterate through each digit for the hundreds place
21 for (let hundredsPlaceIndex = 0; hundredsPlaceIndex < numberOfDigits; ++hundredsPlaceIndex) {
22 // Ensure the hundreds digit is non-zero and it's not the same as tens or unit digits
23 if (digits[hundredsPlaceIndex] === 0 || hundredsPlaceIndex === unitPlaceIndex || hundredsPlaceIndex === tensPlaceIndex) {
24 continue;
25 }
26
27 // Form the three-digit number
28 const number = digits[hundredsPlaceIndex] * 100 + digits[tensPlaceIndex] * 10 + digits[unitPlaceIndex];
29
30 // Add the number to the set to ensure uniqueness
31 uniqueNumbers.add(number);
32 }
33 }
34 }
35
36 // Return the count of unique numbers formed
37 return uniqueNumbers.size;
38}
39
Time and Space Complexity
The time complexity of the code is O(n^3)
because the solution involves three nested loops, each iterating over the entire list digits
. Each loop represents an index selection from the list, resulting in a cubic relationship relative to the length n
of the array.
The space complexity can be considered O(n^3)
in the worst-case scenario where all possible three-digit combinations are unique and added to the set s
. However, the space complexity could be seen as smaller depending on the input constraints and the distinctiveness of the digits since a set naturally handles duplicates. Nonetheless, as per the reference, considering every possibility leads to this space complexity.
Learn more about how to find time and space complexity quickly.
How many times is a tree node visited in a depth first search?
Recommended Readings
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Donβt Miss This!