Skip to content

Commit 5e7bfbb

Browse files
add question no 503
1 parent 79ce8db commit 5e7bfbb

File tree

1 file changed

+222
-0
lines changed

1 file changed

+222
-0
lines changed
Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
---
2+
id: next-greater-element-II
3+
title: Next Greater Element II
4+
sidebar_label: 0503-Next-Greater-Element-II
5+
tags:
6+
- Array
7+
- Stack
8+
- Monotonic Stack
9+
description: "Given a circular integer array nums (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return the next greater number for every element in nums.."
10+
---
11+
12+
## Problem
13+
14+
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return the next greater number for every element in nums.
15+
16+
The next greater number of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
17+
18+
### Examples
19+
20+
**Example 1:**
21+
```
22+
Input: nums = [1,2,1]
23+
Output: [2,-1,2]
24+
Explanation: The first 1's next greater number is 2;
25+
The number 2 can't find next greater number.
26+
The second 1's next greater number needs to search circularly, which is also 2.
27+
```
28+
29+
**Example 2:**
30+
31+
```
32+
Input: nums = [1,2,3,4,3]
33+
Output: [2,3,4,-1,4]
34+
```
35+
36+
### Constraints
37+
38+
- `1 <= nums.length <= 10^4`.
39+
- `-10^9 <= nums[i] <= 10^9`
40+
41+
---
42+
43+
## Solution for Next Greater Element II
44+
45+
46+
### Brute Force - Recursion
47+
48+
#### Intuition
49+
The idea is to make use of an array doublearr which is formed by concatenating two copies of the given array one after the other. Now, when we need to find out the next greater element for `arr[i]`, we can simply scan all the elements `doublearr[j]`. The first element found satisfying the given condition is the required result for `arr[i]`. If no such element is found, we put a `-1` at the appropriate position in the res array.
50+
51+
#### Implementation
52+
- Create an empty vector to store the next greater element for each element in the input array.
53+
Duplicate the input array to create a circular array. This is done by appending the original array to itself.
54+
- Start iterating through each element in the original array.
55+
- For each element in the original array, search for the next greater element in the circular array
56+
starting from the next position after the current element.
57+
- If a greater element is found, update the corresponding index in the result vector with the value
58+
of the greater element. If no greater element is found, keep the index in the result vector as -1.
59+
- Once all elements have been processed, return the result vector containing the next greater
60+
element for each element in the input array.
61+
62+
#### Brute Force Solution
63+
64+
<Tabs>
65+
<TabItem value="Brute Force" label="Brute Force">
66+
67+
#### Implementation
68+
69+
```
70+
class Solution {
71+
public:
72+
vector<int> nextGreaterElement(int N, vector<int>& arr) {
73+
vector<int> res(N, -1);
74+
vector<int> doublearr(arr.begin(), arr.end());
75+
doublearr.insert(doublearr.end(), arr.begin(), arr.end());
76+
for (int i = 0; i < N; i++) {
77+
for (int j = i + 1; j < doublearr.size(); j++) {
78+
if (doublearr[j] > doublearr[i]) {
79+
res[i] = doublearr[j];
80+
break;
81+
}
82+
}
83+
}
84+
return res;
85+
// code here
86+
}
87+
};
88+
```
89+
90+
#### Code in Different Languages
91+
92+
<Tabs>
93+
<TabItem value="Python" label="Python">
94+
<SolutionAuthor name="@himanshukumar"/>
95+
```python
96+
class Solution:
97+
def nextGreaterElement(self, N, arr):
98+
res = [-1] * len(arr)
99+
doublearr = arr + arr
100+
for i in range(len(arr)):
101+
for j in range(i + 1, len(doublearr)):
102+
if doublearr[j] > doublearr[i]:
103+
res[i] = doublearr[j]
104+
break
105+
return res
106+
107+
```
108+
109+
</TabItem>
110+
<TabItem value="Java" label="Java">
111+
<SolutionAuthor name="@himanshukumar"/>
112+
113+
```
114+
class Solution {
115+
static int[] nextGreaterElement(int N, int arr[]) {
116+
int[] res = new int[arr.length];
117+
int[] doublearr = new int[arr.length * 2];
118+
System.arraycopy(arr, 0, doublearr, 0, arr.length);
119+
System.arraycopy(arr, 0, doublearr, arr.length, arr.length);
120+
for (int i = 0; i < arr.length; i++) {
121+
res[i]=-1;
122+
for (int j = i + 1; j < doublearr.length; j++) {
123+
if (doublearr[j] > doublearr[i]) {
124+
res[i] = doublearr[j];
125+
break;
126+
}
127+
}
128+
}
129+
return res;
130+
}
131+
}
132+
133+
```
134+
135+
</TabItem>
136+
<TabItem value="C++" label="C++">
137+
<SolutionAuthor name="@himanshukumar"/>
138+
```cpp
139+
class Solution {
140+
public:
141+
vector<int> nextGreaterElement(int N, vector<int>& arr) {
142+
vector<int> res(N, -1);
143+
vector<int> doublearr(arr.begin(), arr.end());
144+
doublearr.insert(doublearr.end(), arr.begin(), arr.end());
145+
for (int i = 0; i < N; i++) {
146+
for (int j = i + 1; j < doublearr.size(); j++) {
147+
if (doublearr[j] > doublearr[i]) {
148+
res[i] = doublearr[j];
149+
break;
150+
}
151+
}
152+
}
153+
return res;
154+
// code here
155+
}
156+
};
157+
```
158+
159+
</TabItem>
160+
</Tabs>
161+
162+
#### Complexity Analysis
163+
164+
- Time Complexity: $O(N^2)$
165+
- The function iterates through each element in the input array, resulting in $O(N)$ iterations.
166+
For each element, it searches for the next greater element in the circular array, which may require iterating through the entire circular array in the worst case, resulting in another $O(N)$ iterations.
167+
Therefore, the overall time complexity is $O(N^2)$.
168+
- Space Complexity: $O(N)$
169+
- The function creates a duplicate circular array of size $2N$ to handle cases where the next greater element wraps around to the beginning of the array. Therefore, the additional space required is $O(N)$ to store this duplicate array.
170+
- Additionally, the result vector to store the next greater element for each element in the input array also requires $O(N)$ space.
171+
Therefore, the overall space complexity is $O(N)$.
172+
173+
174+
### Optimized Approach
175+
#### Intuition
176+
This approach relies on the concept of a monotonic stack to efficiently find the next greater element for each element in the input array. It iterates through a concatenated version of the array to simulate a circular structure, ensuring that every element's next greater element is considered
177+
178+
#### Approach
179+
- Create a vector ans of size N, initialized with -1. This vector will store the next greater
180+
elements for each element in the input vector arr.
181+
- Create an empty stack st to store indices.
182+
- Iterate through each index i from `0` to `2*N-1` using a for loop.
183+
- Inside the loop, while the stack is not empty and the element at index `arr[st.top()]` is less than the current element `arr[i % N]`, update the ans vector at index `st.top()` with the current
184+
element `arr[i % N]` and pop the top element from the stack.
185+
- Push the current index `i % N` onto the stack.
186+
After the loop, return the ans vector containing the next greater elements for each element in the input vector arr.
187+
188+
<Tabs>
189+
<TabItem value="C++" label="C++">
190+
<SolutionAuthor name="@himanshukumar"/>
191+
```cpp
192+
193+
class Solution {
194+
public:
195+
vector<int> nextGreaterElement(int N, vector<int>& arr) {
196+
vector<int> ans(N, -1);
197+
stack<int> st;
198+
for (int i = 0; i < 2 * N; i++) {
199+
while (!st.empty() and arr[st.top()] < arr[i % N]) {
200+
ans[st.top()] = arr[i % N];
201+
st.pop();
202+
}
203+
st.push(i % N);
204+
}
205+
return ans;
206+
}
207+
};
208+
```
209+
210+
</TabItem>
211+
</Tabs>
212+
213+
#### Complexity Analysis
214+
- Time Complexity: $ O(N)$
215+
- Space Complexity: $ O(N)$
216+
217+
## References
218+
219+
- **LeetCode Problem**: [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/description/)
220+
221+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/next-greater-element-ii/solutions/)
222+

0 commit comments

Comments
 (0)