Created
May 12, 2025 15:58
-
-
Save tatsuyax25/32a2703930a13a9ebccb7af3b7baf812 to your computer and use it in GitHub Desktop.
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 di
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finds all three-digit even numbers that can be formed using the given digits. | |
* @param {number[]} digits - An array of digits (0-9). | |
* @return {number[]} - An array of unique three-digit even numbers. | |
*/ | |
var findEvenNumbers = function(digits) { | |
const arr = []; // Stores valid even numbers | |
const ct = Array(10).fill(0); // Count occurrences of each digit (0-9) | |
// Count frequency of digits in the input array | |
digits.forEach(x => { | |
ct[x] += 1; | |
}); | |
// Possible values for each digit position | |
const pos1 = [1,2,3,4,5,6,7,8,9]; // First digit cannot be 0 | |
const pos2 = [0,1,2,3,4,5,6,7,8,9]; // Second digit can be any value | |
const pos3 = [0,2,4,6,8]; // Last digit must be even | |
const num = [-1, -1, -1]; // Temporary storage for current number | |
// Iterate over possible first digits | |
for(let i = 0; i < pos1.length; i++) { | |
if (ct[pos1[i]] === 0) continue; // Skip if digit is unavailable | |
num[0] = pos1[i]; | |
ct[pos1[i]] -= 1; // Use this digit | |
// Iterate over possible second digits | |
for(let j = 0; j < pos2.length; j++) { | |
if (ct[pos2[j]] === 0) continue; // Skip if digit is unavailable | |
num[1] = pos2[j]; | |
ct[pos2[j]] -= 1; // Use this digit | |
// Iterate over possible third digits (even numbers) | |
for(let k = 0; k < pos3.length; k++) { | |
if (ct[pos3[k]] === 0) continue; // Skip if digit is unavailable | |
// Construct and store the number | |
arr.push(Number(`${num[0]}${num[1]}${pos3[k]}`)); | |
} | |
ct[pos2[j]] += 1; // Restore count for backtracking | |
} | |
ct[pos1[i]] += 1; // Restore count for backtracking | |
} | |
return arr; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment