Back to blog
Dec 05, 2024
2 min read

LeetCode 402: Remove K Digits

Leetcode 402: Remove K Digits solution in Python

Problem Description

LeetCode Problem 402

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

 

Example 1:

Input: num = “1432219”, k = 3 Output: “1219” Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = “10200”, k = 1 Output: “200” Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = “10”, k = 2 Output: “0” Explanation: Remove all the digits from the number and it is left with nothing which is 0.

 

Constraints:

  • 1 <= k <= num.length <= 105
  • num consists of only digits.
  • num does not have any leading zeros except for the zero itself.

Difficulty: Medium

Tags: string, stack, greedy, monotonic stack

Rating: 95.08%

Solution

Here’s my Python solution to this problem:

#Problem 402: Remove K Digits

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        if k >= len(num): return "0"

        stack = []

        for d in num:
            while k > 0 and stack and stack[-1] > d:
                stack.pop()
                k -= 1
            stack.append(d)
        
        # If we still have digits to remove, remove from the end
        # This handles cases like "123456" where digits are in ascending order
        while k > 0:
            stack.pop()
            k -= 1
        
        result = ''.join(stack)
        result = result.lstrip('0')
        return result if result else "0"

Complexity Analysis

The solution has the following complexity characteristics:

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(n)O(n)