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])- A. [3, 18, 1]
- B. [18, 18, 18, 3, 1]
- C. [18, 1, 3]
- 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].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)? python n, lo, hi, it = 200, 0, 200, 0…
- Items E, F, G, H, I, J are pushed onto an empty stack in this order, and a pop may happen at any time. Which pop order is NOT possible?
- Exponential search: double the bound i (1, 2, 4, …) until a[i] ≥ key or i passes the end, then binary-search the last range. How many…
- One Hoare partition with the FIRST element as pivot (i moves right while a[i] < pivot, j moves left while a[j] > pivot, swap while i < j…
- Can a string become a palindrome by deleting at most one character? Two pointers try skipping either side on the first mismatch. What is…
- Binary search with mid = (lo + hi) // 2 (lo = 0, hi = n − 1, loop while lo ≤ hi) looks for 16 in [18, 39, 40, 44, 45, 56, 60, 62, 70, 84…