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)- A. 2219
- B. 1219
- C. 1432
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- 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…
- Children have greed values 7, 8, 9, 10 and cookies have sizes 5, 6, 7, 8, 8. A child is content if the cookie given is at least his greed…
- Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval…
- Job durations (burst times) are 6, 8, 7, 3, 4 with all jobs arriving at time 0. Shortest-job-first runs them one after another in…
- A row of positions 1 to 20 is scanned in order. A position i is picked if no position has been picked yet, or if i minus the last picked…
- Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below…