1
- /* Contributor: Nayan Saraff
1
+ /**
2
+ * Contributor: Nayan Saraff
2
3
*
3
- * This Monotonic Increasing Stack is a popular algorithm which helps
4
- * in solving various problems including Stock Span, Trapping Rain Water
4
+ * A Monotonic Increasing Stack is an algorithmic pattern used to solve
5
+ * problems such as Stock Span, Trapping Rain Water, and Next Greater Element.
6
+ * It maintains a stack where elements are in increasing order to efficiently
7
+ * find relationships between elements based on their relative values.
8
+ *
9
+ * Reference:
10
+ * https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/
5
11
*/
6
12
7
13
import java .util .Stack ;
@@ -12,6 +18,15 @@ private MonotonicIncreasingStack() {
12
18
throw new AssertionError ("Cannot instantiate utility class" );
13
19
}
14
20
21
+ /**
22
+ * Finds the next greater element for each element in the given array.
23
+ *
24
+ * For each element, it returns the nearest greater element to its right.
25
+ * If no such element exists, -1 is returned for that index.
26
+ *
27
+ * Time Complexity: O(n)
28
+ * Space Complexity: O(n)
29
+ */
15
30
public static int [] nextGreaterElement (int [] arr ) {
16
31
int n = arr .length ;
17
32
int [] result = new int [n ];
@@ -27,6 +42,15 @@ public static int[] nextGreaterElement(int[] arr) {
27
42
return result ;
28
43
}
29
44
45
+ /**
46
+ * Finds the next smaller element for each element in the given array.
47
+ *
48
+ * For each element, it returns the nearest smaller element to its right.
49
+ * If no such element exists, -1 is returned for that index.
50
+ *
51
+ * Time Complexity: O(n)
52
+ * Space Complexity: O(n)
53
+ */
30
54
public static int [] nextSmallerElement (int [] arr ) {
31
55
int n = arr .length ;
32
56
int [] result = new int [n ];
@@ -41,6 +65,29 @@ public static int[] nextSmallerElement(int[] arr) {
41
65
}
42
66
return result ;
43
67
}
44
- }
45
68
46
- /* Reference: https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/ */
69
+ // Test class included in the same file
70
+ public static void main (String [] args ) {
71
+ testScenario (new int []{2 , 5 , 1 , 3 , 4 });
72
+ testScenario (new int []{1 , 2 , 3 , 4 , 5 });
73
+ testScenario (new int []{5 , 4 , 3 , 2 , 1 });
74
+ }
75
+
76
+ private static void testScenario (int [] arr ) {
77
+ int [] nextGreater = nextGreaterElement (arr );
78
+ int [] nextSmaller = nextSmallerElement (arr );
79
+
80
+ System .out .print ("Array: " );
81
+ printArray (arr );
82
+ System .out .print ("Next Greater: " );
83
+ printArray (nextGreater );
84
+ System .out .print ("Next Smaller: " );
85
+ printArray (nextSmaller );
86
+ System .out .println ("-----------------------------" );
87
+ }
88
+
89
+ private static void printArray (int [] arr ) {
90
+ for (int n : arr ) System .out .print (n + " " );
91
+ System .out .println ();
92
+ }
93
+ }
0 commit comments