Skip to content

Commit d692051

Browse files
committed
Solution for Next Greatest Element
1 parent 5dd7da3 commit d692051

File tree

4 files changed

+153
-0
lines changed

4 files changed

+153
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# 496. Next Greater Element I
2+
3+
**Difficulty:** Easy
4+
**Category:** Stack, Hash Map, Arrays
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/next-greater-element-i/description/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
Given two arrays `nums1` and `nums2` where `nums1` is a subset of `nums2`, for each element in `nums1`, find the next greater element in `nums2`.
12+
The next greater element of x in `nums2` is the first greater element to the right of x in the same array. If it doesn’t exist, return -1.
13+
14+
---
15+
16+
## 💡 Approach & Key Insights
17+
18+
- Use a stack to find the next greater element for every number in `nums2` efficiently.
19+
- Store the result in a hash map so we can answer each query from `nums1` in constant time.
20+
- This problem leverages the monotonic decreasing stack pattern.
21+
22+
---
23+
24+
## 🛠️ Breakdown of Approaches
25+
26+
### 1️⃣ Brute Force / Naive Approach
27+
28+
- **Explanation:** For each element in `nums1`, search for its index in `nums2` and iterate to the right to find the next greater element.
29+
- **Time Complexity:** O(m * n) - where m = length of nums1, n = length of nums2
30+
- **Space Complexity:** O(1) - no extra space used
31+
- **Example/Dry Run:**
32+
33+
Example input: nums1 = [4,1,2], nums2 = [1,3,4,2]
34+
→ 4: found at index 2, no greater element → -1
35+
→ 1: index 0 → next greater is 3
36+
→ 2: index 3 → no greater → -1
37+
Output: [-1, 3, -1]
38+
39+
### 2️⃣ Optimized Approach
40+
41+
- **Explanation:**
42+
1. Iterate over nums2 in reverse.
43+
2. Use a stack to keep track of next greater elements.
44+
3. Store each number’s NGE in a hashmap.
45+
4. Lookup each element in nums1 using the hashmap.
46+
- **Time Complexity:** O(n + m) - where n = len(nums2), m = len(nums1)
47+
- **Space Complexity:** O(n) - for stack and hashmap
48+
- **Example/Dry Run:**
49+
50+
Example input: nums1 = [2,4], nums2 = [1,2,3,4]
51+
Stack build →
52+
→ 4 → stack: [] → map[4] = -1
53+
→ 3 → stack: [4] → map[3] = 4
54+
→ 2 → stack: [3] → map[2] = 3
55+
→ 1 → stack: [2] → map[1] = 2
56+
Now lookup:
57+
→ 2 → 3
58+
→ 4 → -1
59+
Output: [3, -1]
60+
61+
---
62+
63+
## 📊 Complexity Analysis
64+
65+
| Approach | Time Complexity | Space Complexity |
66+
| ------------- | --------------- | ---------------- |
67+
| Brute Force | O(m * n) | O(1) |
68+
| Optimized | O(n + m) | O(n) |
69+
70+
---
71+
72+
## 📉 Optimization Ideas
73+
74+
- The stack-based approach is already optimal.
75+
- Further improvement is only possible if input constraints change.
76+
77+
---
78+
79+
## 📌 Example Walkthroughs & Dry Runs
80+
81+
```plaintext
82+
Example:
83+
nums1 = [2, 4]
84+
nums2 = [1, 2, 3, 4]
85+
86+
Stack Process:
87+
Start from right:
88+
- 4 → NGE = -1
89+
- 3 → NGE = 4
90+
- 2 → NGE = 3
91+
- 1 → NGE = 2
92+
93+
Hashmap: {1:2, 2:3, 3:4, 4:-1}
94+
95+
Result: [3, -1]
96+
```
97+
98+
---
99+
100+
## 🔗 Additional Resources
101+
102+
- [Stack approach explained visually](https://www.youtube.com/watch?v=68a1Dc_qVq4)
103+
- [Monotonic Stack Pattern](https://leetcode.com/tag/monotonic-stack/)
104+
105+
---
106+
107+
Author: Abdul Wahab
108+
Date: 19/07/2025
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public:
3+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
4+
int n = nums.size();
5+
vector < int > nge(n, -1);
6+
stack < int > st;
7+
for (int i = 2 * n - 1; i >= 0; i--) {
8+
while (!st.empty() && st.top() <= nums[i % n]) {
9+
st.pop();
10+
}
11+
12+
if (i < n) {
13+
if (!st.empty()) nge[i] = st.top();
14+
}
15+
st.push(nums[i % n]);
16+
}
17+
return nge;
18+
}
19+
};
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
3+
Map<Integer, Integer> nge = new HashMap<>();
4+
Stack<Integer> st = new Stack<>();
5+
for (int num : nums2) {
6+
while (!st.isEmpty() && st.peek() < num) {
7+
nge.put(st.pop(), num);
8+
}
9+
st.push(num);
10+
}
11+
int[] res = new int[nums1.length];
12+
for (int i = 0; i < nums1.length; i++) {
13+
res[i] = nge.getOrDefault(nums1[i], -1);
14+
}
15+
return res;
16+
}
17+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
3+
nge = {}
4+
stack = []
5+
for num in nums2:
6+
while stack and stack[-1] < num:
7+
nge[stack.pop()] = num
8+
stack.append(num)
9+
return [nge.get(x, -1) for x in nums1]

0 commit comments

Comments
 (0)