ProgrammingVery hardTCS NQT · Accenture
An array holds the values [3, 0, 2, 0, 1] (positions 0 to 4). The procedure below computes the water trapped above each position as min(leftmax, rightmax) - height, when that is positive, and prints the total. What is printed?
An array holds the values [3, 0, 2, 0, 1] (positions 0 to 4). The procedure below computes the water trapped above each position as min(leftmax, rightmax) - height, when that is positive, and prints the total. What is printed?
leftmax[i] = max of a[0..i]; rightmax[i] = max of a[i..n-1] total = sum over i of max(0, min(leftmax[i], rightmax[i]) - a[i]) Print total
- A. 2
- B. 3
- C. 9
- D. 6
Correct answer: B. 3
Water sits above index 1 (min(3,2) - 0 = 2) and above index 3 (min(2,1) - 0 = 1), so the trapped total is 3. Counting the positions with water gives 2, using the larger side gives 9, and the sum of the heights is 6.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The Fibonacci sequence 1, 1, 2, 3, 5, ... is generated by the loop below, and the procedure prints how many terms are less than or equal…
- The string "aabcccdddd" is compressed by the procedure below, which replaces each run of equal letters by the letter followed by the run…
- The procedure below scans the word "leetcode" from the left and prints the index of the first letter that occurs exactly once in the word…
- The procedure below counts the integers n with 1 <= n <= 60 that are not divisible by 2, 3 or 5 (coprime to 30). What is printed? count =…
- The procedure below counts the pairs i < j in the array [3, 1, 4, 1, 5] whose sum is even. What is printed? count = 0 for i = 0 to n - 2…
- The procedure below collects x mod 5 for every x from 1 to 20 into a set and prints the size of the set. What is printed? seen = empty set…