402. Remove K Digits
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to remove k digits from a given number string num to obtain the smallest possible resulting number. The key insight is that the value of a number is most influenced by its most significant digits (those on the left). For instance, 1xxx is always smaller than 2xxx, regardless of what the x's are. This suggests a greedy approach.
Solution
Remove K Digits in Python
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
# Use a list as a stack to build the result.
stack = []
# Iterate through each digit of the number.
for digit in num:
# While there are digits to remove (k > 0), the stack is not empty,
# and the last digit in the stack is greater than the current digit,
# pop the last digit from the stack.
while k > 0 and stack and stack[-1] > digit:
stack.pop()
k -= 1
# Push the current digit onto the stack.
stack.append(digit)
# After the loop, if k is still > 0, it means the remaining digits are
# in non-decreasing order (e.g., "12345"). We should remove the largest
# digits, which are at the end of the stack.
if k > 0:
stack = stack[:-k]
# Join the stack to form the number string and remove leading zeros.
result = "".join(stack).lstrip('0')
# If the result is empty after stripping zeros (e.g., original was "0", "10" with k=2),
# return "0". Otherwise, return the result.
return result if result else "0"
Remove K Digits in Java
class Solution {
public String removeKdigits(String num, int k) {
// Use a StringBuilder as a stack to build the result.
StringBuilder sb = new StringBuilder();
// Iterate through each digit of the number.
for (char digit : num.toCharArray()) {
// While there are digits to remove (k > 0), the result stack is not empty,
// and the last digit in the result is greater than the current digit,
// pop the last digit from the result.
while (k > 0 && sb.length() > 0 && sb.charAt(sb.length() - 1) > digit) {
sb.deleteCharAt(sb.length() - 1);
k--;
}
// Push the current digit onto the result stack.
sb.append(digit);
}
// After the loop, if k is still > 0, it means the remaining digits are
// in non-decreasing order (e.g., "12345"). We should remove the largest
// digits, which are at the end of the result.
while (k > 0) {
sb.deleteCharAt(sb.length() - 1);
k--;
}
// Find the first non-zero character to handle leading zeros.
int firstNonZero = 0;
while (firstNonZero < sb.length() && sb.charAt(firstNonZero) == '0') {
firstNonZero++;
}
// Create the final result string from the non-zero part.
String result = sb.substring(firstNonZero);
// If the result is empty (e.g., all digits were removed or were zeros),
// return "0". Otherwise, return the result.
return result.length() == 0 ? "0" : result;
}
}
Remove K Digits in C++
class Solution {
public:
string removeKdigits(string num, int k) {
// Use a string as a stack to build the result.
string result = "";
// Iterate through each digit of the number.
for (char digit : num) {
// While there are digits to remove (k > 0), the result stack is not empty,
// and the last digit in the result is greater than the current digit,
// pop the last digit from the result.
while (k > 0 && !result.empty() && result.back() > digit) {
result.pop_back();
k--;
}
// Push the current digit onto the result stack.
result.push_back(digit);
}
// After the loop, if k is still > 0, it means the remaining digits are
// in non-decreasing order (e.g., "12345"). We should remove the largest
// digits, which are at the end of the result.
while (k > 0) {
result.pop_back();
k--;
}
// Find the first non-zero character to handle leading zeros.
size_t first_digit_pos = result.find_first_not_of('0');
// If a non-zero digit is found, create a substring from that position.
// Otherwise, the result is all zeros, so we just take "0".
if (string::npos != first_digit_pos) {
return result.substr(first_digit_pos);
}
// If the result is empty or all zeros, return "0".
return "0";
}
};
Remove K Digits in TypeScript
function removeKdigits(num: string, k: number): string {
// Use an array of strings as a stack to build the result.
const stack: string[] = [];
// Iterate through each digit of the number.
for (const digit of num) {
// While there are digits to remove (k > 0), the stack is not empty,
// and the last digit in the stack is greater than the current digit,
// pop the last digit from the stack.
while (k > 0 && stack.length > 0 && stack[stack.length - 1] > digit) {
stack.pop();
k--;
}
// Push the current digit onto the stack.
stack.push(digit);
}
// After the loop, if k is still > 0, it means the remaining digits are
// in non-decreasing order (e.g., "12345"). We should remove the largest
// digits, which are at the end of the stack.
while (k > 0) {
stack.pop();
k--;
}
// Find the first non-zero character to handle leading zeros.
let firstNonZeroIndex = 0;
while (firstNonZeroIndex < stack.length && stack[firstNonZeroIndex] === '0') {
firstNonZeroIndex++;
}
// Build the result string from the first non-zero digit.
const result = stack.slice(firstNonZeroIndex).join('');
// If the result string is empty (e.g., all digits removed or all were zeros),
// return "0". Otherwise, return the result.
return result === '' ? '0' : result;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.