ProgrammingVery hardTCS NQT · Accenture
The stack-based procedure below computes, for each index i of a = [4, 2, 6, 1, 5], the index of the next greater element to its right (or -1 if there is none), and then prints the sum of these indices. What is printed?
The stack-based procedure below computes, for each index i of a = [4, 2, 6, 1, 5], the index of the next greater element to its right (or -1 if there is none), and then prints the sum of these indices. What is printed?
stack = empty; nxt = [-1] * n
for i = 0 to n - 1
while stack not empty and a[top] < a[i]: nxt[top] = i; pop
push i
end for
Print sum of nxt- A. 5
- B. 15
- C. 6
- D. 0
Correct answer: C. 6
The next greater indices are 2, 2, -1, 4 and -1, so the sum is 6. Using the wrong comparison gives 5, storing values instead of indices gives 15, and forgetting to push indices onto the stack gives 0.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- An array a = [1, 3, 5, 7, 9, 11, 13, 15] is searched with binary search for the target 15, and the procedure counts how many array…
- The procedure below converts the Roman numeral "MCMXCIV" to a number by reading left to right and subtracting a symbol's value when the…
- A recursive function is written as below. The procedure counts the calls made for input 7, including the first call. What is printed?…
- The procedure below uses exponentiation by squaring on the exponent 37. It counts one multiplication into result each time the current…
- Recursive merge sort splits an array of length n into halves of length n div 2 and n minus n div 2, and calls itself on each half unless…
- The loop below multiplies i by 3 each time while i is less than 1000, starting from i = 1, and counts the iterations. What is printed? i =…