Problem
You are given an integer array digits
, where each element is a digit. The array may contain duplicates.
You need to find all the unique integers that follow the given requirements:
- The integer consists of the concatenation of three elements from
digits
in any arbitrary order. - The integer does not have leading zeros.
- The integer is even.
For example, if the given digits
were [1, 2, 3]
, integers 132
and 312
follow the requirements.
Return a sorted array of the unique integers.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
3 <= digits.length <= 100
0 <= digits[i] <= 9
Solution
Method 1 - Generating combinations
To address the problem, let’s break it into steps:
- Generate combinations: Create all possible combinations of three distinct digits from the given array.
- Concatenate digits: For each combination, concatenate the digits in all possible orders. This results in integers formed by concatenating three digits.
- Check requirements:
- Ensure integers do not have leading zeros.
- Ensure integers are even (last digit is divisible by 2).
- Remove duplicates: Use a set data structure to ensure uniqueness of integers.
- Sort the result: Return the sorted list of integers.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^3 × 3!)
, wheren
is the number of digits in the input array.- Generating combinations takes
O(n^3)
since we pick three distinct digits. - Permutation generation for each combination takes
O(3!) = O(6)
. - Filtering conditions are
O(1)
per integer.
- Generating combinations takes
- 🧺 Space complexity:
O(k)
, wherek
is the number of valid integers in the output.