ProgrammingHardTCS NQT · Accenture
Array a = [5, 3, 8, 1] (length 4). The procedure below counts how many elements are leaders, where an element is a leader if it is strictly greater than every element to its right (the last element is always a leader). What is printed?
Array a = [5, 3, 8, 1] (length 4). The procedure below counts how many elements are leaders, where an element is a leader if it is strictly greater than every element to its right (the last element is always a leader). What is printed?
count = 1; mx = a[n-1]
for i = n - 2 down to 0
if a[i] > mx then count = count + 1; mx = a[i]
end for
Print count- A. 2
- B. 1
- C. 4
- D. 3
Correct answer: A. 2
Scanning from the right: 1 is a leader, 8 beats it, 3 does not beat 8, and 5 does not beat 8, so the leaders are 8 and 1, which is 2. Forgetting the last element gives 1, the array length 4 is a different count, and counting values above the last element gives 3.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i…
- Array a = [3, 6, -2, -5, 7, 3]. The procedure below finds the largest product of two adjacent elements. What is printed? best = a[0] a[1]…
- The loop below prints the running count for i = 1, 4, 7, 10, ... up to and including 20 (i increases by 3 each time). What is the number…
- Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal…
- Array a = [1, 1, 2, 2, 2, 3, 4, 4] is sorted. The two-pointer procedure below removes duplicates in place (keeping one copy of each value)…
- Array a = [4, 9, 1, 7, 3]. The procedure below finds the sum of all elements that are greater than the mean of the array. What is printed?…