KatInterview

Right-Side Larger Neighbor Lookup for Selected Values

Stacks & QueuesAuto-graded · 20 test cases
EasyAuto-gradedStacks & Queuesmonotonic-stackhash-maparrays

Last 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 sequence is distinct.
  • Every value in targets is present somewhere in sequence. A value may appear in targets more 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; targets may contain repeats, but each of its values appears in sequence.
  • 1 <= len(sequence) <= 10^4 (an empty targets list should yield an empty list).
  • Values in sequence are 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.