remove-k-digits
Problem
Problem Description
Solution
This problem is a bit tricky, which requires to take care of some cases, using stack to store each character, and for each time, compare the top number with current number, pop out if top > current number, until the end, and continue to pop out top numbers if k still great than 0. steps:
define stack to store each digit, current index idx.
for each current digit, while loop check stock top digits,
if top digit > current digit (num.charAt(idx)), then stack.pop() to remove top, and k-1 to keep track how many digits left to remove.
if top digit < current digit, do nothing. continue
after check stack top digits, push current digit into stack,
stack.push(idx)
continue check next digit, until the last digit,
idx == len
.After checking all digits from num, now check whether already remove k digits, and remove top remaining k digits from stack.
now digits in stack will format the smallest number.
format number from stack.
remove leading 0s from number.
return smallest number.
For example:
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N)
N - the length of string num
Code
Last updated