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?- A. [17, 5, 2] [7]
- B. [16, 17, 4, 3, 5, 2] [7, 7, 7]
- C. [2, 5, 17] [7]
- 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
- Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back…
- Problem: A wallet starts with a positive balance s and then applies the day's changes in order. Find the minimum s such that the running…
- Problem: A warehouse aisle has shelves with weights; find the leftmost 'balance shelf' i such that the total weight strictly to its left…
- Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based…
- Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one…
- Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays…