Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a leader). Leaders are collected while scanning from the right.

Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a leader). Leaders are collected while scanning from the right.
def leaders(a):
    out, best = [], float("-inf")
    for x in reversed(a):
        if x > best:
            out.append(x)
            best = x
    return out[::-1]
print(leaders([16, 17, 4, 3, 5, 2]), leaders([7, 7, 7]))
What is printed?
  1. A. [17, 5, 2] [7]
  2. B. [16, 17, 4, 3, 5, 2] [7, 7, 7]
  3. C. [2, 5, 17] [7]
  4. D. [17, 5, 2] [7, 7, 7]

Correct answer: A. [17, 5, 2] [7]

Scan from the right keeping the largest value seen so far; a value is a leader exactly when it beats that running maximum. For [16, 17, 4, 3, 5, 2]: 2 (leader), 5 > 2 (leader), 3 and 4 fail, 17 > 5 (leader), 16 fails → reversed back: [17, 5, 2]. Because the test is strict, only the last 7 of [7, 7, 7] qualifies. O(n) instead of the O(n²) check-every-suffix approach.

More Coding Interview Problems questions

Exams that ask this topic