ProgrammingHardTCS NQT · Accenture

A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number is as small as possible. The procedure below does this with a stack. What is printed?

A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number is as small as possible. The procedure below does this with a stack. What is printed?
k = 3; stack = empty
for each digit c of the string
    while k > 0 and stack is not empty and top of stack > c
        pop; k = k - 1
    push c
end for
while k > 0: pop; k = k - 1
Print the stack as a string (no leading zeros)
  1. A. 2219
  2. B. 1219
  3. C. 1432
  4. D. 4329

Correct answer: B. 1219

Removing a digit whenever a smaller digit follows makes the leading digits as small as possible. Deleting the first three digits or the last three digits ignores the order, and removing when the top is smaller builds the largest number.

More Pseudocode and Code Tracing questions

Exams that ask this topic