Find next greater element for subset
Company: Pinduoduo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
You are given two integer arrays `query` and `nums`.
- All elements in `nums` are distinct.
- Every element in `query` also appears in `nums`.
For each value `x` in `query`, find the **next greater element** of `x` in `nums`: the first element to the right of `x`'s position in `nums` that is strictly greater than `x`. If no such element exists, return `-1` for that `x`.
Return an array `ans` of the same length as `query`, where `ans[i]` is the next greater element for `query[i]`.
Example:
- `query = [4, 1, 2]`, `nums = [1, 3, 4, 2]` → `ans = [-1, 3, -1]`
Quick Answer: This question evaluates understanding of sequence analysis and array-processing competencies, including mapping elements between arrays, index lookup, and designing efficient order-dependent algorithms for the "next greater element" problem.
For each query value, return the first greater value to its right in nums, or -1.
Examples
Input: ([4, 1, 2], [1, 3, 4, 2])
Expected Output: [-1, 3, -1]
Explanation: Prompt example.
Input: ([2, 4], [1, 2, 3, 4])
Expected Output: [3, -1]
Explanation: One has no greater.