ProgrammingVery hardInfosys · Cognizant

The same stack method is applied to the string 5317 with exactly 2 digits deleted, but now the aim is the LARGEST number. The procedure: while k > 0, the stack is not empty, and the top is smaller than the current digit, pop and decrement k. Push the digit. After the scan, remove the remaining k digits from the end. What is printed?

The same stack method is applied to the string 5317 with exactly 2 digits deleted, but now the aim is the LARGEST number. The procedure: while k > 0, the stack is not empty, and the top is smaller than the current digit, pop and decrement k. Push the digit. After the scan, remove the remaining k digits from the end. What is printed?
k = 2; stack = empty
for each digit c of the string
    while k > 0 and stack not empty and top < c: pop; k = k - 1
    push c
end for
remove the last k digits; print the stack
  1. A. 17
  2. B. 53
  3. C. 57
  4. D. 75

Correct answer: C. 57

Popping the 3 and then the 1 when 7 arrives leaves 5 then 7, so the answer is 57. Deleting the first digits gives 17, deleting the last gives 53, and sorting the digits in descending order gives 75 without respecting positions.

More Pseudocode and Code Tracing questions

Exams that ask this topic