#402

Remove K Digits

Medium
StringStackGreedyMonotonic StackGreedyMonotonic Stack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a greedy strategy with a monotonic stack to efficiently build the smallest number by removing digits. This method ensures that we always keep the smallest possible digits in the result.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty stack to build the result.
  2. 2Step 2: Iterate through each digit in 'num'.
  3. 3Step 3: While the stack is not empty, and the current digit is smaller than the top of the stack, pop the stack if we still have digits to remove (k > 0).
  4. 4Step 4: Push the current digit onto the stack.
  5. 5Step 5: After processing all digits, if k > 0, remove the last k digits from the stack.
  6. 6Step 6: Convert the stack to a string and remove leading zeros.
solution.py15 lines
1# Full working Python code
2from collections import deque
3
4def removeKdigits(num, k):
5    stack = deque()
6    for digit in num:
7        while k > 0 and stack and stack[-1] > digit:
8            stack.pop()
9            k -= 1
10        stack.append(digit)
11    while k > 0:
12        stack.pop()
13        k -= 1
14    result = ''.join(stack).lstrip('0')
15    return result if result else '0'

Complexity note: The time complexity is O(n) because we iterate through the digits once, and the stack operations are O(1) on average. The space complexity is O(n) due to the stack used to build the result.

  • 1Removing larger digits when possible helps in forming the smallest number.
  • 2Leading zeros must be handled carefully to ensure valid output.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.