Data Structures & AlgorithmsHardProduct Company SDE · greedy stack

Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order. Use the monotone-stack code below. What is printed?

Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order. Use the monotone-stack code below. What is printed?
def rm(num, k):
    st = []
    for c in num:
        while k and st and st[-1] > c:
            st.pop()
            k -= 1
        st.append(c)
    st = st[:len(st) - k] if k else st
    return ''.join(st).lstrip('0') or '0'
print(rm('1432219', 3))
  1. A. 1229
  2. B. 1432
  3. C. 1291
  4. D. 1219

Correct answer: D. 1219

The stack removes 4, 3 and then 2 when a smaller digit arrives, leaving 1 2 1 9 after the last removal. Forgetting to strip leading zeros is the other classic slip.

More Coding Interview Problems questions

Exams that ask this topic