Data Structures & AlgorithmsHardGATE CS · DSA
For each element of [16, 4, 2, 19, 10, 6, 29, 9], find the next greater element to its RIGHT (−1 if none), using a monotonic stack. What is the output?
- A. [19, 19, 19, 29, 29, 29, −1, −1]
- B. [−1, 16, 4, −1, 19, 10, −1, 29]
- C. [29, 29, 29, 29, 29, 29, −1, −1]
- D. [−1, −1, 19, −1, −1, 29, −1, −1]
Correct answer: A. [19, 19, 19, 29, 29, 29, −1, −1]
Scan left to right keeping a decreasing stack of indices; when a larger value arrives it resolves every smaller element on the stack. The 'first larger value to the right' is needed — not the largest, and not just the immediate neighbour.
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
- How many distinct non-empty substrings does the string "aaaaa" have, and how many substrings counted by position?
- Find the index of the first non-repeating character using a frequency table (−1 if none). What is printed? python from collections import…
- A string of length n is searched for a pattern of length m. What are the worst-case times of the naive algorithm and of KMP?
- How many inversions (pairs i < j with a[i] > a[j]) does [35, 33, 31, 3, 20, 18, 13, 4] have? (This is also the number of swaps bubble sort…
- The Dutch national flag algorithm (pointers low, mid, high; 0 → swap with low and advance both; 1 → advance mid; 2 → swap with high and…
- A mountain is a contiguous subarray of length ≥ 3 that strictly increases to a single peak and then strictly decreases. What is the length…