Next Greater Element I - Problem
Next Greater Element I is a classic stack-based problem that teaches you how to efficiently find relationships between array elements.
Given two arrays
The next greater element of an element
Example: If
Goal: Return an array where each position contains the next greater element for the corresponding element in
Given two arrays
nums1 and nums2, where nums1 is a subset of nums2, your task is to find the next greater element for each element in nums1.The next greater element of an element
x is the first element to the right of x that is greater than x. If no such element exists, return -1.Example: If
nums2 = [1,3,4,2] and we're looking for the next greater element of 3, the answer is 4 because 4 is the first element to the right of 3 that is greater than 3.Goal: Return an array where each position contains the next greater element for the corresponding element in
nums1. Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [4,1,2], nums2 = [1,3,4,2]
โบ
Output:
[-1,3,-1]
๐ก Note:
For 4: no element to the right is greater, so -1. For 1: first greater element to the right is 3. For 2: no element to the right is greater, so -1.
example_2.py โ All Found
$
Input:
nums1 = [2,4], nums2 = [1,2,3,4]
โบ
Output:
[3,-1]
๐ก Note:
For 2: first greater element to the right is 3. For 4: no element to the right is greater, so -1.
example_3.py โ Single Element
$
Input:
nums1 = [1], nums2 = [1,2]
โบ
Output:
[2]
๐ก Note:
For 1: first greater element to the right is 2.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Stack
Start with an empty stack and empty result map
2
Process Each Element
For each element in nums2, pop smaller elements from stack and map them to current element
3
Add Current Element
Push current element onto stack
4
Handle Remaining
Elements left in stack have no next greater element (-1)
5
Query Results
Look up each element from nums1 in our result map
Key Takeaway
๐ฏ Key Insight: The monotonic stack approach transforms an O(nยฒ) problem into O(n) by maintaining elements in decreasing order and efficiently mapping each element to its next greater neighbor.
Time & Space Complexity
Time Complexity
O(n*m)
For each of n elements in nums1, we potentially scan all m elements in nums2
โ Linear Growth
Space Complexity
O(1)
Only using a few variables, no additional data structures
โ Linear Space
Constraints
- 1 โค nums1.length โค nums2.length โค 1000
- 0 โค nums1[i], nums2[i] โค 104
- All integers in nums1 and nums2 are unique
- All the integers of nums1 also appear in nums2
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code