Right-Side Larger Neighbor Lookup for Selected Values
Stacks & QueuesAuto-graded · 20 test casesLast updated
Tests whether you can precompute the nearest strictly larger value to the right for every element using a monotonic stack, then answer lookups for a chosen list of values.
You are given two integer lists, targets and sequence.
- Every value in
sequenceis distinct. - Every value in
targetsis present somewhere insequence. A value may appear intargetsmore than once.
For a value v located at position p in sequence, its right-side larger neighbor is the first value found while moving right from position p + 1 that is strictly greater than v. If every value to the right of p is smaller than v, or p is the last position, then v has no such neighbor and the answer for it is -1.
Return a list result with the same length as targets, where result[i] is the right-side larger neighbor of targets[i] within sequence, or -1 if none exists.
The value -1 is always the "none" marker, even if -1 also happens to occur in sequence.
Constraints
0 <= len(targets) <= len(sequence)is not guaranteed;targetsmay contain repeats, but each of its values appears insequence.1 <= len(sequence) <= 10^4(an emptytargetslist should yield an empty list).- Values in
sequenceare pairwise distinct integers. - Aim for time better than
O(len(targets) * len(sequence)).
Examples
Example 1
Input: right_larger_lookup([4, 1, 2], [1, 3, 4, 2])
Output: [-1, 3, -1]
Example 2
Input: right_larger_lookup([4, 1, 2], [1, 3, 4, 2])
Output: [-1, 3, -1]
Example 3
Input: right_larger_lookup([2, 4], [1, 2, 3, 4])
Output: [3, -1]
Example 4
Input: right_larger_lookup([1, 3, 5, 2], [5, 4, 3, 2, 1])
Output: [-1, -1, -1, -1]
Hints
Hint 1
Because values in the sequence are distinct, the answer depends only on the value itself, not on which query asked for it. Consider computing answers for every element once.
Hint 2
Scan the sequence left to right while keeping a stack of values that are still waiting for a larger value to appear. What order must the stack maintain?
Hint 3
When a new value arrives, pop every stacked value smaller than it and record the new value as their answer. Anything never popped gets -1. Then answer each target with a dictionary lookup.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since all values in sequence are distinct, each value has exactly one position, so its right-side larger neighbor is a property of the value alone. This lets us ignore which values were queried, compute the answer for every element of sequence in one pass, and then look up each target.
To compute all answers, scan sequence from left to right and maintain a stack of values that have not yet found a larger value to their right. For each new value:
- While the top of the stack is smaller than
value, pop it and recordvalueas its answer. - Push
valueonto the stack, since it is now waiting for its own answer.
Whatever remains on the stack at the end has no larger value to its right and is absent from the dictionary, so a lookup with default -1 gives the required result.
Why it is correct
- The stack is strictly decreasing from bottom to top, because we only push a value after removing everything smaller than it.
- When a value
yis popped byvalue, every element between them arrived whileywas on the stack and did not pop it, so none of them exceededy. Hencevalueis the first larger element to the right ofy. - If some later element were larger than
y, it would reachyafter popping the smaller values above it, soywould be popped. Therefore values never popped truly have no answer.
Edge cases follow naturally: a last element is never popped (-1), a decreasing sequence yields all -1, repeated targets get the same answer, and an empty targets returns an empty list.
Complexity
- Time:
O(n + m), wheren = len(sequence)andm = len(targets). Each element is pushed and popped at most once, and each lookup isO(1)on average. - Space:
O(n)for the stack and dictionary, plusO(m)for the output.
Reference solution
from typing import List
def right_larger_lookup(targets: List[int], sequence: List[int]) -> List[int]:
answers = {}
waiting = []
for value in sequence:
while waiting and waiting[-1] < value:
answers[waiting.pop()] = value
waiting.append(value)
return [answers.get(t, -1) for t in targets]