We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Key of the Numbers

Number: 3568

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given three positive integers num1, num2, and num3, each is first represented as a four-digit string (padding with leading zeros if necessary). The key is a four-digit string where the iᵗʰ digit is the smallest among the iᵗʰ digits of the padded representations of num1, num2, and num3. The output is the key number without any leading zeros (return 0 if the result is "0000").


Key Insights

  • First, normalize each number to a four-digit string by padding with zeros.
  • Compare the corresponding characters (digits) of the three strings.
  • Construct a new string made up of the minimum digit from each corresponding digit.
  • Convert the resulting string to an integer to eliminate any leading zeros.
  • This process is simple and runs in constant time since the operations are fixed (only 4 digits).

Space and Time Complexity

Time Complexity: O(1) – Operations are performed on a fixed-length string (4 digits). Space Complexity: O(1) – Only a few extra string variables are used.


Solution

The solution involves the following steps:

  1. Convert each number to a four-character string using leading zero padding if required.
  2. Iterate from index 0 to 3, and for each index, compare the corresponding digits from each string.
  3. Build the key string using the minimum of the three digits at each position.
  4. Convert the key string to an integer to strip any leading zeros and return the result. The main data structure used is a string for each padded number, and the built-in string manipulation functions are leveraged to construct the key.

Code Solutions

# Function to find the key of the numbers
def find_key(num1, num2, num3):
    # Pad each number to ensure it is represented by exactly 4 digits
    str1 = str(num1).zfill(4)
    str2 = str(num2).zfill(4)
    str3 = str(num3).zfill(4)
    
    # Initialize the key string
    key_str = ""
    
    # Loop through each digit position (0 to 3)
    for i in range(4):
        # Get the i-th digit of each padded string
        digit1 = str1[i]
        digit2 = str2[i]
        digit3 = str3[i]
        # Find the smallest digit among them
        min_digit = min(digit1, digit2, digit3)
        # Append the smallest digit to the key string
        key_str += min_digit
    
    # Convert the key string to an integer to remove any leading zeros
    return int(key_str)

# Example usage:
print(find_key(1, 10, 1000))  # Output: 0
print(find_key(987, 879, 798))  # Output: 777
print(find_key(1, 2, 3))        # Output: 1
← Back to All Questions