Data Structures & AlgorithmsVery hardProduct company OA

A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros dropped). What is printed?

A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros dropped). What is printed?
def smallest(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(smallest("4205173", 3), smallest("10200", 1), smallest("123456", 2))
  1. A. 205 0200 3456
  2. B. 173 200 3456
  3. C. 173 200 1234
  4. D. 0173 200 1234

Correct answer: C. 173 200 1234

Greedy with a non-decreasing stack: whenever an earlier digit is larger than the next one, removing it lowers the most significant possible position. 4205173, k = 3: drop 4 (2 < 4), drop 2 (0 < 2), keep 0, 5, then drop 5 for 1 → 0173 → 173. 10200, k = 1: drop 1 → 0200 → 200. In an increasing string nothing is popped, so the leftover deletions come off the END → 1234 (dropping from the front gives 3456). O(n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic