Next Greater Value From a Reference Sequence
Implement nextGreaterFromReference
You're given two arrays:
queries, a list of values to look up, and reference, a sequence in which every value in queries is guaranteed to appear exactly once. For every value in queries, find the first value in reference that comes strictly after it and is strictly greater — or -1 if none exists.
Looking each query up individually — locate it, then scan forward — repeats the same kind of scan over and over. It's faster to flip the order of work: make a single left-to-right pass over reference with a monotonic decreasing stack, recording every element's "next greater" answer into a map the moment it's discovered (exactly the moment a bigger value causes it to be popped). Once that map is built, every query in the list becomes an O(1) lookup, turning what could be O(n·m) repeated scanning into O(n + m) total work.
Example 1:
Input: queries = [6,3,8], reference = [3,8,6,2,9]
Output: [9,8,9]
Example 2:
Input: queries = [5,2], reference = [2,5,1,6]
Output: [6,5]
Example 3:
Input: queries = [10,7,4], reference = [4,10,7]
Output: [-1,-1,10]
+ 2 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ queries.length ≤ 10 - ●
1 ≤ reference.length ≤ 15 - ●
0 ≤ queries[i], reference[i] ≤ 1000 - ●
All values inside reference are distinct - ●
Every value in queries is guaranteed to appear somewhere in reference
queries =
[6, 3, 8]
reference =
[3, 8, 6, 2, 9]