Skip to content

Commit caa96d6

Browse files
authored
Merge pull request #1443 from agarwalhimanshugaya/dsa2
add question no 503
2 parents 59d7389 + 2b20aaa commit caa96d6

File tree

1 file changed

+225
-0
lines changed

1 file changed

+225
-0
lines changed
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
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+
<Tabs>
46+
<TabItem value="Brute Force" label="Brute Force">
47+
### Brute Force - Recursion
48+
49+
#### Intuition
50+
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.
51+
52+
#### Implementation
53+
- Create an empty vector to store the next greater element for each element in the input array.
54+
Duplicate the input array to create a circular array. This is done by appending the original array to itself.
55+
- Start iterating through each element in the original array.
56+
- For each element in the original array, search for the next greater element in the circular array
57+
starting from the next position after the current element.
58+
- If a greater element is found, update the corresponding index in the result vector with the value
59+
of the greater element. If no greater element is found, keep the index in the result vector as -1.
60+
- Once all elements have been processed, return the result vector containing the next greater
61+
element for each element in the input array.
62+
63+
#### Brute Force Solution
64+
65+
#### Implementation
66+
67+
```
68+
class Solution {
69+
public:
70+
vector<int> nextGreaterElement(int N, vector<int>& arr) {
71+
vector<int> res(N, -1);
72+
vector<int> doublearr(arr.begin(), arr.end());
73+
doublearr.insert(doublearr.end(), arr.begin(), arr.end());
74+
for (int i = 0; i < N; i++) {
75+
for (int j = i + 1; j < doublearr.size(); j++) {
76+
if (doublearr[j] > doublearr[i]) {
77+
res[i] = doublearr[j];
78+
break;
79+
}
80+
}
81+
}
82+
return res;
83+
// code here
84+
}
85+
};
86+
```
87+
88+
#### Code in Different Languages
89+
90+
<Tabs>
91+
<TabItem value="Python" label="Python">
92+
<SolutionAuthor name="@himanshukumar"/>
93+
```python
94+
class Solution:
95+
def nextGreaterElement(self, N, arr):
96+
res = [-1] * len(arr)
97+
doublearr = arr + arr
98+
for i in range(len(arr)):
99+
for j in range(i + 1, len(doublearr)):
100+
if doublearr[j] > doublearr[i]:
101+
res[i] = doublearr[j]
102+
break
103+
return res
104+
105+
```
106+
107+
</TabItem>
108+
<TabItem value="Java" label="Java">
109+
<SolutionAuthor name="@himanshukumar"/>
110+
111+
```
112+
class Solution {
113+
static int[] nextGreaterElement(int N, int arr[]) {
114+
int[] res = new int[arr.length];
115+
int[] doublearr = new int[arr.length * 2];
116+
System.arraycopy(arr, 0, doublearr, 0, arr.length);
117+
System.arraycopy(arr, 0, doublearr, arr.length, arr.length);
118+
for (int i = 0; i < arr.length; i++) {
119+
res[i]=-1;
120+
for (int j = i + 1; j < doublearr.length; j++) {
121+
if (doublearr[j] > doublearr[i]) {
122+
res[i] = doublearr[j];
123+
break;
124+
}
125+
}
126+
}
127+
return res;
128+
}
129+
}
130+
131+
```
132+
133+
</TabItem>
134+
<TabItem value="C++" label="C++">
135+
<SolutionAuthor name="@himanshukumar"/>
136+
```cpp
137+
class Solution {
138+
public:
139+
vector<int> nextGreaterElement(int N, vector<int>& arr) {
140+
vector<int> res(N, -1);
141+
vector<int> doublearr(arr.begin(), arr.end());
142+
doublearr.insert(doublearr.end(), arr.begin(), arr.end());
143+
for (int i = 0; i < N; i++) {
144+
for (int j = i + 1; j < doublearr.size(); j++) {
145+
if (doublearr[j] > doublearr[i]) {
146+
res[i] = doublearr[j];
147+
break;
148+
}
149+
}
150+
}
151+
return res;
152+
// code here
153+
}
154+
};
155+
```
156+
157+
</TabItem>
158+
</Tabs>
159+
160+
#### Complexity Analysis
161+
162+
- Time Complexity: $O(N^2)$
163+
- The function iterates through each element in the input array, resulting in $O(N)$ iterations.
164+
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.
165+
Therefore, the overall time complexity is $O(N^2)$.
166+
- Space Complexity: $O(N)$
167+
- 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.
168+
- Additionally, the result vector to store the next greater element for each element in the input array also requires $O(N)$ space.
169+
Therefore, the overall space complexity is $O(N)$.
170+
171+
</TabItem>
172+
<TabItem value="Optimized Approach " label="Optimized Approach ">
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+
</TabItem>
218+
</Tabs>
219+
220+
## References
221+
222+
- **LeetCode Problem**: [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/description/)
223+
224+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/next-greater-element-ii/solutions/)
225+

0 commit comments

Comments
 (0)