Next Greater Element I
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
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
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Approach 1
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.⏱ O(M * N) where M is nums1.length and N is nums2.length.💾 O(1) excluding the output array.
Approach 2
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.⏱ O(N + M*N) worst case, but faster in practice.💾 O(N) to store indices of nums2.
Approach 3
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.⏱ O(N + M) where N is nums2.length, M is nums1.length💾 O(N)
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.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.