Facebook Pixel

3270. Find the Key of the Numbers

Problem Description

You are given three positive integers num1, num2, and num3. Your task is to generate a special "key" from these three numbers.

The key is created following these rules:

  1. Padding with zeros: First, each number is treated as having exactly 4 digits. If any number has fewer than 4 digits, add leading zeros to make it 4 digits long. For example:

    • 25 becomes 0025
    • 123 becomes 0123
    • 4567 stays 4567
  2. Finding minimum digits: For each digit position (1st, 2nd, 3rd, and 4th), compare the corresponding digits from all three padded numbers and take the smallest one:

    • For the 1st digit position, find the minimum among the 1st digits of all three numbers
    • For the 2nd digit position, find the minimum among the 2nd digits of all three numbers
    • Continue this for all 4 positions
  3. Building the key: Combine these minimum digits to form a 4-digit key.

  4. Removing leading zeros: Return the final key as an integer (which automatically removes any leading zeros).

Example: If num1 = 1234, num2 = 5678, and num3 = 91:

  • After padding: 1234, 5678, 0091
  • 1st position (leftmost): min(1, 5, 0) = 0
  • 2nd position: min(2, 6, 0) = 0
  • 3rd position: min(3, 7, 9) = 3
  • 4th position (rightmost): min(4, 8, 1) = 1
  • Key before removing leading zeros: 0031
  • Final answer: 31
Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that we need to process each digit position independently and find the minimum across all three numbers for that position. Instead of converting numbers to strings and padding them, we can work directly with the numbers using integer arithmetic.

To extract a specific digit from a number, we can use the formula: (number // k) % 10, where k represents the place value (1 for units, 10 for tens, 100 for hundreds, 1000 for thousands). This formula works because:

  • Dividing by k shifts the desired digit to the units place
  • Taking modulo 10 extracts just that digit

For numbers with fewer than 4 digits, this approach naturally gives us 0 for the missing higher-order digits, which is exactly what we want (equivalent to padding with leading zeros).

We can build the answer digit by digit, starting from the units place. For each position:

  1. Extract the corresponding digit from all three numbers
  2. Find the minimum among these three digits
  3. Add this minimum digit to our answer at the correct position by multiplying it with the current place value k

By iterating through all 4 digit positions (units, tens, hundreds, thousands) and accumulating the result, we construct the key directly as an integer. This approach automatically handles the removal of leading zeros since we're building an integer rather than a string.

The beauty of this solution is that it avoids string manipulation entirely and works purely with arithmetic operations, making it both efficient and elegant.

Learn more about Math patterns.

Solution Approach

We implement the solution through direct simulation of the key generation process using integer arithmetic operations.

Algorithm Steps:

  1. Initialize variables:

    • ans = 0: Store the final key value
    • k = 1: Represent the current place value (starts at 1 for units place)
  2. Process each digit position (4 iterations):

    • For each iteration, we extract the current digit from all three numbers using the formula: num // k % 10
      • num // k shifts the desired digit to the rightmost position
      • % 10 extracts just that single digit
    • Calculate the minimum digit: x = min(num1 // k % 10, num2 // k % 10, num3 // k % 10)
    • Add this minimum digit to the answer at the correct position: ans += x * k
    • Move to the next digit position by multiplying k by 10: k *= 10
  3. Return the result:

    • The accumulated ans is our final key, already in integer form without leading zeros

Example walkthrough with num1 = 1234, num2 = 5678, num3 = 91:

  • Iteration 1 (units place, k=1):

    • Extract: 1234 % 10 = 4, 5678 % 10 = 8, 91 % 10 = 1
    • Minimum: 1
    • Update: ans = 0 + 1*1 = 1
  • Iteration 2 (tens place, k=10):

    • Extract: 123 % 10 = 3, 567 % 10 = 7, 9 % 10 = 9
    • Minimum: 3
    • Update: ans = 1 + 3*10 = 31
  • Iteration 3 (hundreds place, k=100):

    • Extract: 12 % 10 = 2, 56 % 10 = 6, 0 % 10 = 0
    • Minimum: 0
    • Update: ans = 31 + 0*100 = 31
  • Iteration 4 (thousands place, k=1000):

    • Extract: 1 % 10 = 1, 5 % 10 = 5, 0 % 10 = 0
    • Minimum: 0
    • Update: ans = 31 + 0*1000 = 31

The time complexity is O(1) since we always iterate exactly 4 times, and the space complexity is O(1) as we only use a constant amount of extra space.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a small example with num1 = 87, num2 = 4, and num3 = 512.

Step 1: Conceptual Padding

  • 870087 (padded with two leading zeros)
  • 40004 (padded with three leading zeros)
  • 5120512 (padded with one leading zero)

Step 2: Process Each Digit Position

We'll use the formula (number // k) % 10 to extract digits, where k is the place value.

Iteration 1 - Units place (k = 1):

  • Extract digits: 87 % 10 = 7, 4 % 10 = 4, 512 % 10 = 2
  • Find minimum: min(7, 4, 2) = 2
  • Update answer: ans = 0 + 2 * 1 = 2

Iteration 2 - Tens place (k = 10):

  • Extract digits: (87 // 10) % 10 = 8, (4 // 10) % 10 = 0, (512 // 10) % 10 = 1
  • Find minimum: min(8, 0, 1) = 0
  • Update answer: ans = 2 + 0 * 10 = 2

Iteration 3 - Hundreds place (k = 100):

  • Extract digits: (87 // 100) % 10 = 0, (4 // 100) % 10 = 0, (512 // 100) % 10 = 5
  • Find minimum: min(0, 0, 5) = 0
  • Update answer: ans = 2 + 0 * 100 = 2

Iteration 4 - Thousands place (k = 1000):

  • Extract digits: (87 // 1000) % 10 = 0, (4 // 1000) % 10 = 0, (512 // 1000) % 10 = 0
  • Find minimum: min(0, 0, 0) = 0
  • Update answer: ans = 2 + 0 * 1000 = 2

Step 3: Final Result The key is 2. Note how the integer arithmetic naturally handled the leading zeros - we built the key as 0002 conceptually, but since we're working with integers, it automatically becomes 2.

Solution Implementation

1class Solution:
2    def generateKey(self, num1: int, num2: int, num3: int) -> int:
3        # Initialize the result key and position multiplier
4        result_key = 0
5        position_multiplier = 1
6      
7        # Process each of the 4 digit positions (ones, tens, hundreds, thousands)
8        for digit_position in range(4):
9            # Extract the current digit from each number using integer division and modulo
10            # position_multiplier helps us access the correct digit position
11            digit_from_num1 = (num1 // position_multiplier) % 10
12            digit_from_num2 = (num2 // position_multiplier) % 10
13            digit_from_num3 = (num3 // position_multiplier) % 10
14          
15            # Find the minimum digit among the three numbers at this position
16            min_digit = min(digit_from_num1, digit_from_num2, digit_from_num3)
17          
18            # Add the minimum digit to the result at the current position
19            result_key += min_digit * position_multiplier
20          
21            # Move to the next digit position (ones -> tens -> hundreds -> thousands)
22            position_multiplier *= 10
23      
24        return result_key
25
1class Solution {
2    /**
3     * Generates a key by taking the minimum digit at each position from three numbers.
4     * The key is formed by comparing digits at the same position (units, tens, hundreds, thousands)
5     * and selecting the smallest digit for that position.
6     * 
7     * @param num1 First integer (assumed to be 4 digits or less)
8     * @param num2 Second integer (assumed to be 4 digits or less)
9     * @param num3 Third integer (assumed to be 4 digits or less)
10     * @return The generated key formed by minimum digits at each position
11     */
12    public int generateKey(int num1, int num2, int num3) {
13        int resultKey = 0;
14        int positionMultiplier = 1;
15      
16        // Process 4 digit positions (units, tens, hundreds, thousands)
17        for (int digitPosition = 0; digitPosition < 4; digitPosition++) {
18            // Extract the digit at current position from each number
19            int digitFromNum1 = (num1 / positionMultiplier) % 10;
20            int digitFromNum2 = (num2 / positionMultiplier) % 10;
21            int digitFromNum3 = (num3 / positionMultiplier) % 10;
22          
23            // Find the minimum digit among the three numbers at this position
24            int minDigit = Math.min(Math.min(digitFromNum1, digitFromNum2), digitFromNum3);
25          
26            // Add the minimum digit to the result at the appropriate position
27            resultKey += minDigit * positionMultiplier;
28          
29            // Move to the next digit position (multiply by 10)
30            positionMultiplier *= 10;
31        }
32      
33        return resultKey;
34    }
35}
36
1class Solution {
2public:
3    int generateKey(int num1, int num2, int num3) {
4        int result = 0;
5        int placeValue = 1;
6      
7        // Process each digit position (ones, tens, hundreds, thousands)
8        for (int digitPosition = 0; digitPosition < 4; ++digitPosition) {
9            // Extract the current digit from each number
10            int digit1 = (num1 / placeValue) % 10;
11            int digit2 = (num2 / placeValue) % 10;
12            int digit3 = (num3 / placeValue) % 10;
13          
14            // Find the minimum digit among the three numbers at this position
15            int minDigit = min({digit1, digit2, digit3});
16          
17            // Add the minimum digit to the result at the current place value
18            result += minDigit * placeValue;
19          
20            // Move to the next digit position (multiply by 10)
21            placeValue *= 10;
22        }
23      
24        return result;
25    }
26};
27
1/**
2 * Generates a key by taking the minimum digit at each position from three numbers
3 * @param num1 - First input number
4 * @param num2 - Second input number  
5 * @param num3 - Third input number
6 * @returns The generated key formed by minimum digits at each position
7 */
8function generateKey(num1: number, num2: number, num3: number): number {
9    let result: number = 0;
10    let placeValue: number = 1;
11  
12    // Process 4 digits from right to left (ones, tens, hundreds, thousands)
13    for (let digitPosition: number = 0; digitPosition < 4; digitPosition++) {
14        // Extract the current digit from each number at the current position
15        const digit1: number = Math.floor(num1 / placeValue) % 10;
16        const digit2: number = Math.floor(num2 / placeValue) % 10;
17        const digit3: number = Math.floor(num3 / placeValue) % 10;
18      
19        // Find the minimum digit among the three
20        const minDigit: number = Math.min(digit1, digit2, digit3);
21      
22        // Add the minimum digit to the result at the appropriate position
23        result += minDigit * placeValue;
24      
25        // Move to the next digit position (multiply by 10)
26        placeValue *= 10;
27    }
28  
29    return result;
30}
31

Time and Space Complexity

The time complexity is O(1) because the loop runs exactly 4 times regardless of the input values. Each iteration performs a constant number of operations: integer division (//), modulo operation (%), finding minimum of 3 values, multiplication, and addition. Since the number of iterations is fixed at 4, the overall time complexity remains constant.

The space complexity is O(1) because the algorithm only uses a fixed amount of extra space. The variables ans, k, and x are the only additional variables created, and their memory usage doesn't scale with the input size. No additional data structures like arrays or recursive call stacks are used.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Misunderstanding Digit Position Order

The Problem: A common mistake is confusing the digit extraction order. The algorithm processes digits from right to left (units → tens → hundreds → thousands), but the problem description talks about "1st, 2nd, 3rd, 4th positions" which might be interpreted as left to right.

Why It Happens: When we see "1st position" in the problem, it's natural to think of the leftmost digit, but the algorithm actually builds the number from the rightmost digit first.

Incorrect Implementation:

# Wrong: Trying to process from left to right
def generateKey(self, num1: int, num2: int, num3: int) -> int:
    # Pad numbers to 4 digits as strings
    s1 = str(num1).zfill(4)
    s2 = str(num2).zfill(4)
    s3 = str(num3).zfill(4)
  
    result = ""
    for i in range(4):
        result += str(min(int(s1[i]), int(s2[i]), int(s3[i])))
  
    return int(result)

Correct Approach: The given solution correctly processes digits from right to left using modulo arithmetic, which naturally handles the padding with zeros implicitly.

Pitfall 2: Incorrect Handling of Numbers Greater Than 9999

The Problem: If any input number has more than 4 digits, the algorithm should only consider the rightmost 4 digits, but developers might incorrectly try to process all digits.

Example: If num1 = 12345, we should treat it as 2345 (last 4 digits), not try to process all 5 digits.

Incorrect Implementation:

# Wrong: Doesn't handle numbers > 9999 correctly
def generateKey(self, num1: int, num2: int, num3: int) -> int:
    # This would fail for numbers with more than 4 digits
    digits = max(len(str(num1)), len(str(num2)), len(str(num3)))
    result = 0
    k = 1
    for _ in range(digits):  # Wrong: should always be 4 iterations
        # ... rest of logic

Correct Approach: The solution correctly limits processing to exactly 4 digits by using a fixed loop of 4 iterations, automatically handling both padding for small numbers and truncation for large numbers.

Pitfall 3: Overcomplicating with String Operations

The Problem: Using string manipulation for padding and digit extraction when integer arithmetic is simpler and more efficient.

Why It's Problematic:

  • String operations add unnecessary complexity
  • Type conversions between string and integer can introduce bugs
  • Less efficient than pure arithmetic operations

Correct Approach: The solution elegantly uses (num // position_multiplier) % 10 to extract digits, which:

  • Automatically treats missing digits as 0 (implicit padding)
  • Avoids string conversions
  • Works uniformly for all input sizes
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More