LeetCode 3270: Find the Key of the Numbers

Math

Problem Description

Explanation:

To find the key of the numbers, we need to compare the corresponding digits of the three given numbers and pick the smallest digit at each position to form the key. We can achieve this by iterating through the digits of the numbers and building the key digit by digit.

  1. Convert the numbers to strings and pad them with leading zeros if necessary to make them four digits long.
  2. Iterate through each digit position from 0 to 3.
  3. At each position, compare the digits of num1, num2, and num3 to find the smallest digit.
  4. Append the smallest digit to the key.
  5. Return the key without leading zeros.

The time complexity of this approach is O(1) since we are only dealing with numbers up to four digits, and the space complexity is also O(1).

:

Solutions

class Solution {
    public String findTheKey(int num1, int num2, int num3) {
        String strNum1 = String.format("%04d", num1);
        String strNum2 = String.format("%04d", num2);
        String strNum3 = String.format("%04d", num3);
        
        StringBuilder key = new StringBuilder();
        
        for (int i = 0; i < 4; i++) {
            int minDigit = Math.min(Math.min(Character.getNumericValue(strNum1.charAt(i)), 
                                          Character.getNumericValue(strNum2.charAt(i))),
                                    Character.getNumericValue(strNum3.charAt(i)));
            key.append(minDigit);
        }
        
        return key.toString().replaceFirst("^0+(?!$)", "");
    }
}

Loading editor...