Skip to content
BytePatterns

Next Greater Value Lookup

EasyStacks & Queues#monotonic-stack#hash-map~15m

Problem

You are given a list nums of distinct integers and a list queries whose values all appear somewhere in nums. For each query value, find the first value to its right in nums that is larger than it, or -1 when no larger value follows. Return the answers in query order.

Examples

Input:  nums = [4, 1, 3, 6, 2, 5], queries = [1, 3, 2, 6]
Output: [3, 6, 5, -1]
Why:    1 is followed by 3, 3 by 6 and 2 by 5, while nothing after 6 is larger
Input:  nums = [5, 4, 3, 2, 1], queries = [4, 1]
Output: [-1, -1]
Why:    the list only falls, so no value ever has a larger one after it
Input:  nums = [7], queries = [7]
Output: [-1]
Why:    edge case, a single value has nothing to its right

Hints

0 / 3

Stuck on the idea rather than the code? Monotonic Stack covers it.