Next Greater Element I

Practice this coding question on Coding Gurukul.

Problem statement

A conveyor records distinct parcel priorities in arrival order. For selected parcels, a supervisor asks which later parcel is the first one with a strictly greater priority. Your task For every value in nums1, locate it in nums2 and return the first strictly greater value to its right in nums2. Return -1 when no such value exists. Important details Both arrays contain distinct values, and nums1 is a subset of nums2. The answer is the first greater value in position order, not the greatest later value. Aim for O(n+m) time with a monotonic stack. Worked example For queries [4, 1] and conveyor [1, 3, 4, 2], 4 has no greater value to its right, while 1 first encounters 3. Print -1 3.

Input format

First line: m n. Next m integers: nums1. Next n integers: nums2.

Output format

Print the resulting values in order, separated by spaces. Print EMPTY if there are no values.

Constraints

1 <= m <= n <= 1000; 0 <= values <= 10000; arrays have distinct values and nums1 is a subset.

Sample input

2 4
4 1
1 3 4 2

Sample output

-1 3

Sign in to run or submit a solution in C++, Java or Python.