Skip to content

Commit dbb652b

Browse files
committed
Added Stack NGE
1 parent b520eae commit dbb652b

File tree

1 file changed

+52
-3
lines changed

1 file changed

+52
-3
lines changed

Prepration/Stack/01-Problem-Set.txt

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,19 @@ Problem Set:
99

1010

1111
So, Basically all of these are Problems are similar with minor Variations.
12+
13+
How to Identify whether in a problem, Stack can be Applied or not.
14+
15+
i. Having an Array
16+
ii. If we apply brute force, it gives o(n^2) time. (i.e more precisely if inner loops depends on outer loop.)
1217

1318
1. Nearest Greater Element to Left : Here we have to find the next Immediate Greater element to the Left Side.
1419

1520
Ex : N = 8, arr[] = {10, 3, 0, 1, 15, 0, 2, 4}
1621

1722
o/p : {-1, 10, 3, 3, -1, 15, 15, 15 }
1823

19-
Approach 1 --> This can be solved in O(n^2) time complexity by running 2 for Loop, where for each element we will run the loop to sear ch the nearest greater element on the left side.
24+
Approach 1 --> This can be solved in O(n^2) time complexity by running 2 for Loop, where for each element we will run the loop to search the nearest greater element on the left side.
2025

2126
// Code
2227
public static int[] nextGreaterToLeft(int[] arr, int size) {
@@ -63,9 +68,53 @@ Problem Set:
6368

6469
2. Nearest Greater Element to Right
6570

66-
Approach 1 --> Applying the Brute Force.
71+
Approach 1 --> Applying the Brute Force, This can be solved in O(n^2) time complexity by running 2 for Loop, where for each element we will run the loop to search the nearest greater element on the right side.
72+
73+
//code
74+
public static int[] nextGreaterToRight(int[] arr, int size) {
75+
int[] ngr = new int[size];
76+
for (int i = 0; i < size; i++) {
77+
int max = -1;
78+
for (int j = i+1; j < size; j++) {
79+
if (arr[j] > arr[i]) {
80+
max = arr[j];
81+
break;
82+
}
83+
}
84+
ngr[i] = max;
85+
}
86+
return ngr;
87+
}
88+
89+
Time Complexity --> O( N ^ 2)
90+
91+
Approach 2 --> By using Stack
92+
i. if stack is empty , -1
93+
ii. keep poping the elements which are smaller than the current element.
94+
iii. print top element of stack if stack not empty else print -1.
95+
iv. Reverse the answer.
96+
97+
//code
98+
public int[] nextGreaterToRight(int[] arr, int size) {
99+
int[] ngr = new int[size];
100+
Stack<Integer> stack = new Stack<>();
101+
for (int i = size-1; i >= 0; i--) {
102+
if (!stack.isEmpty()) {
103+
while(!stack.isEmpty() && stack.peek() <= arr[i]) {
104+
stack.pop();
105+
}
106+
}
107+
ngr[i] = stack.isEmpty() ? -1 : stack.peek();
108+
stack.push(arr[i]);
109+
}
110+
return ngr;
111+
}
112+
113+
Time Complexity --> O(N)
114+
115+
116+
67117

68-
Time Complexity --> O( N ^ 2)
69118

70119

71120

0 commit comments

Comments
 (0)