Find the Key of the Numbers
EasyPrompt
You are given three positive integers num1, num2, and num3.
The key of num1, num2, and num3 is defined as a four-digit number such that:
- Initially, if any number has less than four digits, it is padded with leading zeros.
- The
ithdigit (1 <= i <= 4) of thekeyis generated by taking the smallest digit among theithdigits ofnum1,num2, andnum3.
Return the key of the three numbers without leading zeros (if any).
Example 1:
Input: num1 = 1, num2 = 10, num3 = 1000
Output: 0
Explanation:
On padding, num1 becomes "0001", num2 becomes "0010", and num3 remains "1000".
- The
1stdigit of thekeyismin(0, 0, 1). - The
2nddigit of thekeyismin(0, 0, 0). - The
3rddigit of thekeyismin(0, 1, 0). - The
4thdigit of thekeyismin(1, 0, 0).
Hence, the key is "0000", i.e. 0.
Example 2:
Input: num1 = 987, num2 = 879, num3 = 798
Output: 777
Example 3:
Input: num1 = 1, num2 = 2, num3 = 3
Output: 1
Constraints:
1 <= num1, num2, num3 <= 9999
Approaches
2 approaches with complexity analysis and trade-offs.
This approach directly translates the problem description into code. It involves converting the numbers to strings, padding them with leading zeros to ensure a four-digit format, and then iterating through the digits to build the key.
Algorithm
- Convert
num1,num2, andnum3to stringss1,s2, ands3, padding each with leading zeros to a length of 4. - Initialize an empty
StringBuildercalledkeyString. - Loop from
i = 0to3:- Get the characters
c1 = s1.charAt(i),c2 = s2.charAt(i),c3 = s3.charAt(i). - Find the minimum character
minCharamongc1,c2, andc3. - Append
minChartokeyString.
- Get the characters
- Convert
keyStringto a string and then parse it as an integer. - Return the resulting integer.
Walkthrough
The core idea is to leverage string formatting to handle the padding requirement easily. First, we convert each integer num1, num2, and num3 into a four-digit string with leading zeros. For example, in Java, String.format("%04d", num) achieves this. Next, we iterate from the first to the fourth digit (index 0 to 3). In each iteration, we extract the character at the current index from all three strings. We find the minimum of these three characters. Since characters '0' through '9' are ordered sequentially in ASCII, a direct comparison using Math.min() works. The resulting minimum character is appended to a StringBuilder which is used to construct the key string. Finally, after the loop completes, the StringBuilder contains the four-digit key as a string. We convert this string back to an integer using Integer.parseInt(), which automatically handles any leading zeros in the final key (e.g., "0777" becomes 777).
class Solution { public int findKey(int num1, int num2, int num3) { // Pad numbers with leading zeros to make them 4-digit strings String s1 = String.format("%04d", num1); String s2 = String.format("%04d", num2); String s3 = String.format("%04d", num3); StringBuilder keyString = new StringBuilder(); // Iterate through each digit position for (int i = 0; i < 4; i++) { // Get the i-th digit from each number char c1 = s1.charAt(i); char c2 = s2.charAt(i); char c3 = s3.charAt(i); // Find the smallest digit (character comparison works) char minChar = (char) Math.min(c1, Math.min(c2, c3)); // Append the smallest digit to the key keyString.append(minChar); } // Convert the final key string to an integer return Integer.parseInt(keyString.toString()); }}Complexity
Time
O(1) - The operations (string formatting, looping 4 times, parsing) are all constant time because the number of digits is fixed at 4.
Space
O(1) - The space required for the padded strings and the `StringBuilder` is constant (4 characters each), not dependent on the magnitude of the input numbers (within the given constraints).
Trade-offs
Pros
Simple to understand and implement as it directly follows the problem's definition.
Code is highly readable and self-documenting.
Handles the zero-padding requirement elegantly using built-in string formatting functions.
Cons
Involves multiple type conversions (int to string, string to int) and string object allocations, which can be less performant than pure arithmetic operations.
Uses more memory due to the creation of intermediate string objects.
This approach avoids string conversions entirely and relies on mathematical operations to extract and compare digits. It iteratively builds the final key number by processing digits from most significant (thousands) to least significant (ones).
Algorithm
- Initialize
key = 0andplaceValue = 1000. - Loop four times (e.g.,
while (placeValue > 0)):- Extract the most significant digit from each number:
digit1 = num1 / placeValue,digit2 = num2 / placeValue,digit3 = num3 / placeValue. - Find the minimum digit:
minDigit = min(digit1, digit2, digit3). - Append
minDigitto thekey:key = key * 10 + minDigit. - Update the numbers by removing the most significant digit:
num1 = num1 % placeValue, etc. - Update the place value for the next iteration:
placeValue = placeValue / 10.
- Extract the most significant digit from each number:
- Return the final
key.
Walkthrough
The strategy is to calculate the digits of the key one by one, from left to right, and construct the final integer result progressively. We can iterate four times, representing the four digit positions: thousands, hundreds, tens, and ones. A placeValue variable (starting at 1000 and divided by 10 in each step) helps in extracting the correct digit. In each iteration, we calculate the i-th digit of each number. For a number num and a placeValue (e.g., 1000), the digit is num / placeValue. This works because integer division truncates the result. For example, 987 / 1000 is 0, and 1234 / 1000 is 1, correctly giving the thousands digit. We find the minimum of the three extracted digits and append this minimum digit to our result key by using the formula key = key * 10 + minDigit. To prepare for the next iteration, we must remove the digit we just processed from each number using the modulo operator: num = num % placeValue. After four iterations, the key variable will hold the final integer result.
class Solution { public int findKey(int num1, int num2, int num3) { int key = 0; int placeValue = 1000; while (placeValue > 0) { // Extract the digit at the current place value int digit1 = num1 / placeValue; int digit2 = num2 / placeValue; int digit3 = num3 / placeValue; // Find the smallest digit int minDigit = Math.min(digit1, Math.min(digit2, digit3)); // Build the key key = key * 10 + minDigit; // Remove the processed digit from each number num1 %= placeValue; num2 %= placeValue; num3 %= placeValue; // Move to the next smaller place value placeValue /= 10; } return key; }}Complexity
Time
O(1) - The loop runs a fixed 4 times, and all operations inside are constant-time arithmetic operations.
Space
O(1) - Only a fixed number of integer variables are used, regardless of the input values.
Trade-offs
Pros
Highly efficient as it uses only integer arithmetic, avoiding the overhead of string creation and manipulation.
Minimal memory usage, requiring only a few integer variables.
Cons
The logic involving division and modulo to extract and update digits can be less intuitive to write and understand compared to the direct string manipulation approach.
Slightly more prone to off-by-one or logical errors if not implemented carefully (e.g., handling the loop termination and place value updates).
Solutions
Solution
class Solution {public int generateKey(int num1, int num2, int num3) { int ans = 0, k = 1; for (int i = 0; i < 4; ++i) { int x = Math.min(Math.min(num1 / k % 10, num2 / k % 10), num3 / k % 10); ans += x * k; k *= 10; } return ans; }}class Solution {public: int generateKey(int num1, int num2, int num3) { int ans = 0, k = 1; for (int i = 0; i < 4; ++i) { int x = min({num1 / k % 10, num2 / k % 10, num3 / k % 10}); ans += x * k; k *= 10; } return ans; }};class Solution: def generateKey(self, num1: int, num2: int, num3: int) -> int: ans, k = 0, 1 for _ in range(4): x = min(num1 // k % 10, num2 // k % 10, num3 // k % 10) ans += x * k k *= 10 return ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.