Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty).

Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty).
def remove_k(num, k):
    st = []
    for d in num:
        while k and st and st[-1] > d:
            st.pop(); k -= 1
        st.append(d)
    st = st[:len(st) - k]
    return ''.join(st).lstrip('0') or '0'
print(remove_k("1432219", 3), remove_k("10200", 1), remove_k("12345", 2))
What is printed?
  1. A. 1219 0200 123
  2. B. 1219 200 123
  3. C. 1229 200 345
  4. D. 1219 200 345

Correct answer: B. 1219 200 123

Greedy monotonic stack: drop a digit whenever a smaller digit follows it. "1432219" → 1219. "10200" → drop 1 → "0200" → strip zeros → 200. For increasing "12345" nothing is popped, so the leftover k removes digits from the end: 123. O(n).

More Coding Interview Problems questions

Exams that ask this topic