Greedy Algorithms8 sections · 316 units
Open in Course

Remove K Digits - Implementation

The code

function removeKdigits(num, k)
 stack := []
 for each digit in num
 while stack is not empty and k > 0 and stack.top() > digit
 stack.pop()
 k := k - 1
 stack.push(digit)
 while k > 0
 stack.pop()
 k := k - 1
 // Build result and strip leading zeros
 result := ""
 leadingZero := true
 for each d in stack
 if d = '0' and leadingZero then
 continue
 leadingZero := false
 result := result + d
 if result = "" then
 return "0"
 return result

Time: O(n)O(n). Space: O(n)O(n).