Skip to content

Commit b723d53

Browse files
authored
Merge pull request #1534 from tanyagupta01/next-greater-element-i
Create 0496-next-greater-element-I.md
2 parents 36ca738 + 1d6728c commit b723d53

File tree

1 file changed

+167
-0
lines changed

1 file changed

+167
-0
lines changed
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
---
2+
id: next-greater-element-I
3+
title: Next Greater Element I
4+
sidebar_label: 0496-next-greater-element-I
5+
tags:
6+
- Array
7+
- Hash Table
8+
- Stack
9+
- Monotonic Stack
10+
description: "This is a solution to the next greater element I problem on LeetCode."
11+
---
12+
13+
## Problem Description
14+
15+
The next greater element of some element `x` in an array is the first greater element that is to the right of `x` in the same array.
16+
17+
You are given two distinct 0-indexed integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
18+
19+
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the next greater element of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
20+
21+
Return an array `ans` of length `nums1.length` such that `ans[i]` is the next greater element as described above.
22+
23+
### Examples
24+
25+
**Example 1:**
26+
27+
```
28+
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
29+
Output: [-1,3,-1]
30+
Explanation: The next greater element for each value of nums1 is as follows:
31+
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
32+
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
33+
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
34+
```
35+
36+
**Example 2:**
37+
38+
```
39+
Input: nums1 = [2,4], nums2 = [1,2,3,4]
40+
Output: [3,-1]
41+
Explanation: The next greater element for each value of nums1 is as follows:
42+
- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
43+
- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.
44+
```
45+
46+
### Constraints
47+
48+
- `1 <= nums1.length <= nums2.length <= 1000`
49+
- `0 <= nums1[i], nums2[i] <= 104`
50+
- All integers in `nums1` and `nums2` are unique.
51+
- All the integers of `nums1` also appear in `nums2`.
52+
53+
54+
## Solution for Assign Cookies
55+
56+
### Approach:
57+
The intuitive approach to solve this problem is by using a stack. First, we will iterate through nums2 because this is the array where we're finding the next greater elements. As we want to find the next greater element that occurs after the given element, the stack allows us to keep track of the elements we've seen but haven't yet found a greater element for.
58+
59+
Here is the step-by-step intuition behind the solution:
60+
61+
1. We will create a dictionary called m to map each element in nums2 to its next greater element. This will help in quickly looking up the result for each element in nums1.
62+
63+
2. We will also create an empty stack, stk, to maintain the elements for which we have to find the next greater element.
64+
65+
3. We go through each element v in nums2. For every element v, we do the following:
66+
67+
If the stack is not empty, we check the last element in the stack. If the last element in the stack is less than v, it means that v is the next greater element for that stack's top element. So we pop the top from the stack and record v as the next greater element in our dictionary m.
68+
We continue to compare v with the new top of the stack and do the above step until the stack is empty or the top of the stack is no longer less than v.
69+
We push v onto the stack because we need to find the next greater element for it.
70+
71+
4. Once we have completely processed nums2 in the above way, we have our m dictionary with the next greater elements for all elements in nums2 where they exist.
72+
73+
5. Finally, for each element v in nums1, we look up our dictionary m. If v is in the dictionary, we put m[v] in the result array; otherwise, we put -1.
74+
75+
This approach effectively tracks the elements that are yet to find their next greater element and finds the valid greater elements for them in a single pass through nums2 due to the stack's LIFO property.
76+
77+
78+
## Code in Different Languages
79+
80+
<Tabs>
81+
<TabItem value="cpp" label="C++">
82+
<SolutionAuthor name="@tanyagupta01"/>
83+
84+
```cpp
85+
class Solution {
86+
public:
87+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
88+
vector<int> ans;
89+
unordered_map<int, int> numToNextGreater;
90+
stack<int> stack; // a decreasing stack
91+
92+
for (const int num : nums2) {
93+
while (!stack.empty() && stack.top() < num)
94+
numToNextGreater[stack.top()] = num, stack.pop();
95+
stack.push(num);
96+
}
97+
98+
for (const int num : nums1)
99+
if (const auto it = numToNextGreater.find(num);
100+
it != numToNextGreater.cend())
101+
ans.push_back(it->second);
102+
else
103+
ans.push_back(-1);
104+
105+
return ans;
106+
}
107+
};
108+
```
109+
</TabItem>
110+
<TabItem value="java" label="Java">
111+
<SolutionAuthor name="@tanyagupta01"/>
112+
113+
```java
114+
class Solution {
115+
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
116+
List<Integer> ans = new ArrayList<>();
117+
Map<Integer, Integer> numToNextGreater = new HashMap<>();
118+
Deque<Integer> stack = new ArrayDeque<>(); // a decreasing stack
119+
120+
for (final int num : nums2) {
121+
while (!stack.isEmpty() && stack.peek() < num)
122+
numToNextGreater.put(stack.pop(), num);
123+
stack.push(num);
124+
}
125+
126+
for (final int num : nums1)
127+
if (numToNextGreater.containsKey(num))
128+
ans.add(numToNextGreater.get(num));
129+
else
130+
ans.add(-1);
131+
132+
return ans.stream().mapToInt(Integer::intValue).toArray();
133+
}
134+
}
135+
```
136+
137+
</TabItem>
138+
<TabItem value="python" label="Python">
139+
<SolutionAuthor name="@tanyagupta01"/>
140+
141+
```python
142+
class Solution:
143+
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
144+
numToNextGreater = {}
145+
stack = [] # a decreasing stack
146+
147+
for num in nums2:
148+
while stack and stack[-1] < num:
149+
numToNextGreater[stack.pop()] = num
150+
stack.append(num)
151+
152+
return [numToNextGreater.get(num, -1) for num in nums1]
153+
```
154+
</TabItem>
155+
</Tabs>
156+
157+
## Complexity Analysis
158+
159+
### Time Complexity: O(n)
160+
161+
### Space Complexity: O(n)
162+
163+
## References
164+
165+
- **LeetCode Problem**: [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/description/)
166+
167+
- **Solution Link**: [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/solutions/)

0 commit comments

Comments
 (0)