You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Prepration/Stack/01-Problem-Set.txt
+52-3Lines changed: 52 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -9,14 +9,19 @@ Problem Set:
9
9
10
10
11
11
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.)
12
17
13
18
1. Nearest Greater Element to Left : Here we have to find the next Immediate Greater element to the Left Side.
14
19
15
20
Ex : N = 8, arr[] = {10, 3, 0, 1, 15, 0, 2, 4}
16
21
17
22
o/p : {-1, 10, 3, 3, -1, 15, 15, 15 }
18
23
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.
20
25
21
26
// Code
22
27
public static int[] nextGreaterToLeft(int[] arr, int size) {
@@ -63,9 +68,53 @@ Problem Set:
63
68
64
69
2. Nearest Greater Element to Right
65
70
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) {
0 commit comments