Next Greater Element I

Easy · Stack & Strings · Array · Hash Table · Stack · Monotonic Stack

Problem

For a value x in an array, its next greater element is the first value to the right of x that is strictly larger than x.

You are given two arrays of distinct integers, nums1 and nums2, where every value of nums1 also appears in nums2. For each nums1[i], find where it sits in nums2 and take its next greater element there, or -1 if none exists.

Return an array ans of length len(nums1) where ans[i] is the answer for nums1[i]. Aim for O(len(nums1) + len(nums2)) time.

Examples

Input: nums1 = [3,8,5], nums2 = [5,3,8,6,9]
Output: [8,9,8]

In nums2, 3 is followed by 8, 8 by 9 (6 is smaller), and 5 by 8 (3 is smaller).

Input: nums1 = [7,2], nums2 = [2,7]
Output: [-1,7]

Nothing follows 7, while 2 is followed by the larger 7.

Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]

2 is followed by 3. 4 is last, so it has no answer.

Constraints

Approaches

Follow-up

What if nums2 is circular, so the search wraps around to the start? Walk the array twice, pushing only during the first pass. And what if values repeat? Key the answers by index instead of by value.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…