Problem 3270 Find the Key of Numbers
Table of Contents
Problem Statement
Link - Problem 3270
Question
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
ith digit(1 <= i <= 4)of thekeyis generated by taking the smallest digit among theith digits 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 1st digit of the key is min(0, 0, 1).
The 2nd digit of the key is min(0, 0, 0).
The 3rd digit of the key is min(0, 1, 0).
The 4th digit of the key is min(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`
Solution
class Solution {
public:
int generateKey(int num1, int num2, int num3) {
std::ios::sync_with_stdio(false);
string str1 = addzeros(num1);
string str2 = addzeros(num2);
string str3 = addzeros(num3);
string key = "";
for (int i = 0; i < 4; ++i) {
char mindigit = min({str1[i], str2[i], str3[i]});
key += mindigit;
}
return stoi(key);
}
string addzeros(int num) {
string str = to_string(num);
while (str.length() < 4) {
str = "0" + str;
}
return str;
}
};
Complexity Analysis
| Algorithm | Time Complexity | Space Complexity |
| --------- | --------------- | ---------------- |
| Traverse | O(1) | O(1) |
Explanation
1. Intuition
This is a simple problem where we need to just implement what the question asks for. There is no need for any complex algorithm.
- For easy manipulation, we convert the numbers to strings and add leading zeros.
- We then iterate over the strings and find the minimum digit at each position.
- We then return the key as an integer.
2. Implementation
- Convert the numbers to strings and store as
str1,str2, andstr3. - Declare a string
keyto store the key. - Iterate over the strings and find the minimum digit at each position.
- Find the minimum digit at the
ith position ofstr1,str2, andstr3. - Append the minimum digit to the
key.
- Find the minimum digit at the
- Convert the
keyto an integer and return it.