Next Greater Element I
Master this topic with zero to advance depth.
Next Greater Element I
Find the next greater element for each element in nums1 within nums2. The next greater element of x in nums2 is the first element to its right that is larger than x.
Visual Representation
nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2]
Processing nums2 to find next greater:
1. 1: Stack [1]
2. 3: 3 > 1. Map[1]=3. Pop, Push 3. Stack [3]
3. 4: 4 > 3. Map[3]=4. Pop, Push 4. Stack [4]
4. 2: 2 < 4. Push 2. Stack [4, 2]
Result Map: {1:3, 3:4}
For nums1: 4 -> -1, 1 -> 3, 2 -> -1
Output: [-1, 3, -1]Examples
Level I: Brute Force (Nested Loops)
Intuition
For each element in nums1, find its position in nums2, then linearly scan rightward to find the first element greater than it. Simple, but performs redundant scans.
Level II: Pre-located Search (Map + Scan)
Intuition
Instead of linearly searching for each element of nums1 in nums2 every time, we can pre-store the indices of all elements in nums2 in a hash map. This allows us to jump directly to the correct starting point in nums2 for the scan, eliminating the 'find index' part of the brute force.
Level III: Optimal (Monotonic Stack + HashMap)
Intuition
Use a monotonic decreasing stack to find the next greater element for all elements in nums2 in a single pass. Store the results in a hash map for O(1) lookups when processing nums1.
Detailed Dry Run
| Num (nums2) | Stack | Map Update | Action |
|---|---|---|---|
| 1 | [1] | - | Push |
| 3 | [3] | 1 -> 3 | Pop 1, Push 3 |
| 4 | [4] | 3 -> 4 | Pop 3, Push 4 |
| 2 | [4, 2] | - | Push |
⚠️ Common Pitfalls & Tips
Ensure nums1 is actually a subset of nums2 as per problem constraints. The stack approach only works for finding the next greater element.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.