Data Structures & AlgorithmsModerateGATE CS · DSA

Find the leaders (elements strictly greater than everything to their right) by scanning from the right. What is printed?

Find the leaders (elements strictly greater than everything to their right) by scanning from the right. What is printed?
a = [18, 2, 3, 18, 10, 7, 18, 3, 1]
best, out = float("-inf"), []
for x in reversed(a):
    if x > best: out.append(x); best = x
print(out[::-1])
  1. A. [3, 18, 1]
  2. B. [18, 18, 18, 3, 1]
  3. C. [18, 1, 3]
  4. D. [18, 3, 1]

Correct answer: D. [18, 3, 1]

Scanning right to left, an element is a leader when it beats the running maximum; ties are not leaders under the strict rule. Output: [18, 3, 1].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic