Talentd
FleetCode
Make and follow sheets.Sign in

Find the Key of the Numbers solution and explanation

EasyMath6 min read76.1% acceptanceUpdated 9 Apr 2026
3270. Find the Key of the Numbers (Leetcode Easy)Programming Live with Larry · 5:11 · 291 viewsWatch on YouTube
6 more videos on this problem
  1. 3270. Find the Key of the Numbers (Leetcode Easy)Programming Live with Larry · 5:11 · 291 views
  2. leetcode 3270 : key to the numbers : python solutionleetcode blind 75 · 2:26 · 224 views
  3. Leetcode 3270 | Find the Key of the Numbers ✅✅✅ | Step-by-Step Solution | Detail Explanation | ✅✅✅ErDelhiBoy · 11:02 · 164 views
  4. 3270. Find the Key of the NumbersLeetcode and Interview Question · 4:07 · 134 views
  5. Find the Key of the Numbers (LeetCode 3270) | Full solution with visuals | Interview EssentialCodeacademy · 11:06 · 102 views
  6. Biweekly Contest 138 | First 2 Problems | 3270 and 3271 | LeetcodeAmit Choraria · 10:17 · 58 views
  7. Leetcode easy problem 3270. Find the Key of the Numbers | devops python practiceADevOpsEngineer · 1:10 · 9 views

The problem

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 the key is generated by taking the smallest digit among the ith digits of num1, num2, and num3.

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

Approach overview

Problem Overview: You receive three integers. Treat each as a 4-digit number (pad with leading zeros if necessary). For every digit position (thousands, hundreds, tens, ones), pick the smallest digit among the three numbers. Combine those minimum digits to form the final 4-digit key.

Approach 1: Basic Approach with String Manipulation (O(d) time, O(d) space)

This method converts each number into a string and ensures it has exactly four characters using leading zeros. You iterate from index 0 to 3, compare the digits from the three strings at the same position, and select the minimum. Append the smallest digit to a result string and convert the final string back to an integer.

The key insight is that digit positions must align. Converting to strings makes this trivial because indexing directly represents each place value. This approach is straightforward to implement and easy to debug, which is why many developers prefer it in interviews when clarity matters.

Approach 2: Bitwise Operations and Mathematical Approach (O(d) time, O(1) space)

This version avoids strings entirely and works directly with digits using arithmetic operations. Repeatedly extract the last digit of each number using % 10. Compute the minimum among those digits, then build the result number using positional multiplication. After processing a digit, remove it from each number using integer division / 10.

You repeat this process four times (since the key always has four digits). The result is constructed by multiplying the chosen minimum digit with the correct place value (1, 10, 100, 1000). This approach uses constant memory and relies purely on numeric operations from math. It is typically faster in low-level implementations because it avoids string allocation.

Even though the platform labels this as a bitwise-style approach, the core idea is digit extraction through arithmetic. It demonstrates strong understanding of number manipulation, which often appears in math and bit manipulation style problems.

Recommended for interviews: The mathematical digit extraction approach is usually preferred. It uses constant extra space and shows that you understand how numbers are represented digit-by-digit. The string method still demonstrates correct reasoning and is perfectly acceptable for an easy problem, especially if the focus is readability rather than micro-optimizations. Understanding both approaches helps when similar digit-processing problems appear in string or numeric manipulation tasks.

Approach 1: Basic Approach with String Manipulation

In this approach, the main idea is to convert each of the numbers into a four-digit string, padded with leading zeros if needed. Then, by iterating over corresponding digits of each number, we can compute the result by taking the minimum digit at each position. Finally, any leading zeros from the result should be trimmed to adhere to the output requirements.

def find_key(num1, num2, num3):
    str1 = f'{num1:04}'; str2 = f'{num2:04}'; str3 = f'{num3:04}'
    key = ''.join(min(str1[i], str2[i], str3[i]) for i in range(4))
    return key.lstrip('0') or '0'

print(find_key(1, 10, 1000)) # Output: 0
print(find_key(987, 879, 798)) # Output: 777
print(find_key(1, 2, 3)) # Output: 1
public class FindKey {
    public static String findKey(int num1, int num2, int num3) {
        String str1 = String.format("%04d", num1);
        String str2 = String.format("%04d", num2);
        String str3 = String.format("%04d", num3);
        
        StringBuilder key = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            char minDigit = (char) Math.min(str1.charAt(i), Math.min(str2.charAt(i), str3.charAt(i)));
            key.append(minDigit);
        }
        
        String result = key.toString().replaceFirst("^0+(?!$)", "");
        return result;
    }

    public static void main(String[] args) {
        System.out.println(findKey(1, 10, 1000)); // Output: 0
        System.out.println(findKey(987, 879, 798)); // Output: 777
        System.out.println(findKey(1, 2, 3)); // Output: 1
    }
}
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

std::string findKey(int num1, int num2, int num3) {
    std::ostringstream oss1, oss2, oss3;
    oss1 << std::setw(4) << std::setfill('0') << num1;
    oss2 << std::setw(4) << std::setfill('0') << num2;
    oss3 << std::setw(4) << std::setfill('0') << num3;
    
    std::string s1 = oss1.str();
    std::string s2 = oss2.str();
    std::string s3 = oss3.str();
    
    std::string key;
    for (int i = 0; i < 4; ++i) {
        char minimum = std::min({s1[i], s2[i], s3[i]});
        key.push_back(minimum);
    }
    
    key.erase(0, key.find_first_not_of('0'));
    return key.empty() ? "0" : key;
}

int main() {
    std::cout << findKey(1, 10, 1000) << std::endl; // Output: 0
    std::cout << findKey(987, 879, 798) << std::endl; // Output: 777
    std::cout << findKey(1, 2, 3) << std::endl; // Output: 1
    return 0;
}
function findKey(num1, num2, num3) {
    const str1 = num1.toString().padStart(4, '0');
    const str2 = num2.toString().padStart(4, '0');
    const str3 = num3.toString().padStart(4, '0');
    
    let key = '';
    for (let i = 0; i < 4; i++) {
        key += Math.min(str1[i], str2[i], str3[i]);
    }
    
    return key.replace(/^0+/, '') || '0';
}

console.log(findKey(1, 10, 1000)); // Output: 0
console.log(findKey(987, 879, 798)); // Output: 777
console.log(findKey(1, 2, 3)); // Output: 1
#include <stdio.h>
#include <string.h>

char* findKey(int num1, int num2, int num3) {
    static char key[5];
    char str1[5], str2[5], str3[5];
    
    sprintf(str1, "%04d", num1);
    sprintf(str2, "%04d", num2);
    sprintf(str3, "%04d", num3);
    
    for (int i = 0; i < 4; i++) {
        key[i] = str1[i];
        if (str2[i] < key[i]) key[i] = str2[i];
        if (str3[i] < key[i]) key[i] = str3[i];
    }
    key[4] = '\0';
    
    int index = 0;
    while (key[index] == '0' && index < 3) {
        index++;
    }
    return key + index;
}

int main() {
    printf("%s\n", findKey(1, 10, 1000)); // Output: 0
    printf("%s\n", findKey(987, 879, 798)); // Output: 777
    printf("%s\n", findKey(1, 2, 3)); // Output: 1
    return 0;
}
using System;

class FindKey {
    static string FindKeyFunc(int num1, int num2, int num3) {
        string str1 = num1.ToString("D4");
        string str2 = num2.ToString("D4");
        string str3 = num3.ToString("D4");
        
        char[] key = new char[4];
        for (int i = 0; i < 4; i++) {
            key[i] = Math.Min(Math.Min(str1[i], str2[i]), str3[i]);
        }
        
        string result = new string(key).TrimStart('0');
        return result.Length == 0 ? "0" : result;
    }

    public static void Main() {
        Console.WriteLine(FindKeyFunc(1, 10, 1000)); // Output: 0
        Console.WriteLine(FindKeyFunc(987, 879, 798)); // Output: 777
        Console.WriteLine(FindKeyFunc(1, 2, 3)); // Output: 1
    }
}

This implementation utilizes Python's formatted string literals to create zero-padded strings for each number. A list comprehension is used to create the key by selecting the minimum digit at each position. The lstrip method is then used to remove any leading zeros, ensuring the result isn't an empty string.

Complexity

Time Complexity: O(1).
Space Complexity: O(1).

Try this approach in the editor

Approach 2: Bitwise Operations and Mathematical Approach

This approach is based on handling the digits through bitwise operations and direct mathematical calculations without converting numbers to strings. This helps in environments where low-level operations are preferred. The idea is to extract individual digits from each number, compare them, and construct the final key purely with arithmetic operations.

def find_key(num1, num2, num3):
    mul = 1000
    result = 0
    while mul > 0:
        d1 = (num1 // mul) % 10
        d2 = (num2 // mul) % 10
        d3 = (num3 // mul) % 10
        min_digit = min(d1, d2, d3)
        result = result * 10 + min_digit
        mul //= 10
    return result

print(find_key(1, 10, 1000)) # Output: 0
print(find_key(987, 879, 798)) # Output: 777
print(find_key(1, 2, 3)) # Output: 1
public class FindKey {
    public static int findKey(int num1, int num2, int num3) {
        int result = 0;
        int mul = 1000;
        for (int i = 0; i < 4; i++) {
            int d1 = (num1 / mul) % 10;
            int d2 = (num2 / mul) % 10;
            int d3 = (num3 / mul) % 10;
            
            int minDigit = Math.min(d1, Math.min(d2, d3));
            result = result * 10 + minDigit;
            
            mul /= 10;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(findKey(1, 10, 1000)); // Output: 0
        System.out.println(findKey(987, 879, 798)); // Output: 777
        System.out.println(findKey(1, 2, 3)); // Output: 1
    }
}
#include <iostream>

int findKey(int num1, int num2, int num3) {
    int digits[4] = {0};
    int factor = 1000;
    for (int i = 0; i < 4; ++i) {
        int d1 = (num1 / factor) % 10;
        int d2 = (num2 / factor) % 10;
        int d3 = (num3 / factor) % 10;
        
        digits[i] = std::min({d1, d2, d3});
        factor /= 10;
    }
    int key = 0, mul = 1000;
    for (int i = 0; i < 4; ++i) {
        key += digits[i] * mul;
        mul /= 10;
    }
    return key;
}

int main() {
    std::cout << findKey(1, 10, 1000) << "\n"; // Output: 0
    std::cout << findKey(987, 879, 798) << "\n"; // Output: 777
    std::cout << findKey(1, 2, 3) << "\n"; // Output: 1
    return 0;
}
function findKey(num1, num2, num3) {
    let factor = 1000;
    let key = 0;
    while (factor >= 1) {
        const d1 = Math.floor(num1 / factor) % 10;
        const d2 = Math.floor(num2 / factor) % 10;
        const d3 = Math.floor(num3 / factor) % 10;
        
        const minDigit = Math.min(d1, d2, d3);
        key = key * 10 + minDigit;
        factor = Math.floor(factor / 10);
    }
    return key;
}

console.log(findKey(1, 10, 1000)); // Output: 0
console.log(findKey(987, 879, 798)); // Output: 777
console.log(findKey(1, 2, 3)); // Output: 1
#include <stdio.h>

int findKey(int num1, int num2, int num3) {
    int digits[4] = {0,0,0,0};
    
    int factor = 1000;
    for(int i = 0; i < 4; ++i) {
        int d1 = (num1 / factor) % 10;
        int d2 = (num2 / factor) % 10;
        int d3 = (num3 / factor) % 10;
        
        digits[i] = d1;
        if (d2 < digits[i])
            digits[i] = d2;
        if (d3 < digits[i])
            digits[i] = d3;
        
        factor /= 10;
    }
    
    int key = 0, place = 1000;
    for (int i = 0; i < 4; ++i) {
        key += digits[i] * place;
        place /= 10;
    }
    return key;
}

int main() {
    printf("%d\n", findKey(1, 10, 1000)); // Output: 0
    printf("%d\n", findKey(987, 879, 798)); // Output: 777
    printf("%d\n", findKey(1, 2, 3)); // Output: 1
    return 0;
}
using System;

class FindKey {
    static int FindKeyFunc(int num1, int num2, int num3) {
        int key = 0;
        int mul = 1000;
        for (int i = 0; i < 4; ++i) {
            int d1 = (num1 / mul) % 10;
            int d2 = (num2 / mul) % 10;
            int d3 = (num3 / mul) % 10;
            
            int minDigit = Math.Min(Math.Min(d1, d2), d3);
            key = key * 10 + minDigit;
            
            mul /= 10;
        }
        return key;
    }

    public static void Main() {
        Console.WriteLine(FindKeyFunc(1, 10, 1000)); // Output: 0
        Console.WriteLine(FindKeyFunc(987, 879, 798)); // Output: 777
        Console.WriteLine(FindKeyFunc(1, 2, 3)); // Output: 1
    }
}

This code avoids converting numbers to strings and instead calculates each digit using division and modulo operations, adding each minimum digit to the result variable, thereby efficiently computing the desired key.

Complexity

Time Complexity: O(1).
Space Complexity: O(1).

Try this approach in the editor

Approach 3: Simulation

We can directly simulate this process by defining a variable ans to store the answer and a variable k to represent the current digit place, where k = 1 represents the units place, k = 10 represents the tens place, and so on.

Starting from the units place, for each digit place, we calculate the current digit of num1, num2, and num3, take the minimum of the three, and then add this minimum value multiplied by k to the answer. Then, multiply k by 10 and continue to the next digit place.

Finally, return the answer.

The time complexity is O(1), and the space complexity is O(1).

function generateKey(num1: number, num2: number, num3: number): number {
    let [ans, k] = [0, 1];
    for (let i = 0; i < 4; ++i) {
        const x = Math.min(((num1 / k) | 0) % 10, ((num2 / k) | 0) % 10, ((num3 / k) | 0) % 10);
        ans += x * k;
        k *= 10;
    }
    return ans;
}
func generateKey(num1 int, num2 int, num3 int) (ans int) {
	k := 1
	for i := 0; i < 4; i++ {
		x := min(min(num1/k%10, num2/k%10), num3/k%10)
		ans += x * k
		k *= 10
	}
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Basic Approach with String Manipulation

Time Complexity: O(1).
Space Complexity: O(1).

Bitwise Operations and Mathematical Approach

Time Complexity: O(1).
Space Complexity: O(1).

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
String ManipulationO(d)O(d)Best for readability and quick implementation using string indexing
Mathematical Digit ExtractionO(d)O(1)Preferred when optimizing memory and working directly with digits

Frequently asked questions

Is Find the Key of the Numbers easy or hard?

Find the Key of the Numbers is categorized as an Easy problem. It mainly tests understanding of digit positions, simple comparisons, and number manipulation. Most solutions are implemented in a few lines using either string processing or basic math.

Find the Key of the Numbers Python/Java solution

In Python or Java, convert numbers to 4-digit strings and compare digits position by position, or repeatedly extract digits using % 10 and / 10. The minimum digit from the three numbers at each place forms the final key. Both implementations run in constant time due to the fixed number of digits.

How to solve Find the Key of the Numbers in O(n)?

Treat each number as a 4-digit value and process one digit position at a time. Extract digits either by string indexing or by using modulo and division operations. Compute the minimum digit among the three numbers at each position and append it to the result key. The algorithm runs in O(d) time with constant space when using arithmetic operations.

What is the best approach for Find the Key of the Numbers?

The mathematical digit extraction approach is typically considered the best. It processes each digit using modulo (% 10) and division (/ 10) operations and builds the result numerically. The algorithm runs in O(d) time where d is the number of digits (4 here) and uses O(1) extra space.

Is Find the Key of the Numbers asked at Google/Amazon/Meta?

This problem belongs to the easy math category and is mainly used for practice on digit manipulation and basic algorithmic thinking. Similar digit-processing problems appear in interviews at companies like Amazon and Google, especially in early screening rounds.

What data structure is used in Find the Key of the Numbers?

No complex data structures are required. The solution mainly relies on basic arithmetic operations or simple string manipulation. The core concept comes from math-based digit extraction and positional comparison.

What is the time complexity of Find the Key of the Numbers?

Both common solutions run in O(d) time where d is the number of digits in the numbers. Since the problem always works with 4-digit values, the runtime is effectively constant. Space complexity is O(d) for the string method and O(1) for the mathematical approach.

Comments

Now write it yourselfClose this page and solve Find the Key of the Numbers in the editor, without looking.
Practise Find the Key of the Numbers