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
  1. A. 2
  2. B. 1
  3. C. 4
  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.

More Pseudocode and Code Tracing questions

Exams that ask this topic