1- /* Contributor: Nayan Saraff
1+ /**
2+ * Contributor: Nayan Saraff
23 *
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/
511 */
612
713import java .util .Stack ;
@@ -12,6 +18,15 @@ private MonotonicIncreasingStack() {
1218 throw new AssertionError ("Cannot instantiate utility class" );
1319 }
1420
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+ */
1530 public static int [] nextGreaterElement (int [] arr ) {
1631 int n = arr .length ;
1732 int [] result = new int [n ];
@@ -27,6 +42,15 @@ public static int[] nextGreaterElement(int[] arr) {
2742 return result ;
2843 }
2944
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+ */
3054 public static int [] nextSmallerElement (int [] arr ) {
3155 int n = arr .length ;
3256 int [] result = new int [n ];
@@ -41,6 +65,29 @@ public static int[] nextSmallerElement(int[] arr) {
4165 }
4266 return result ;
4367 }
44- }
4568
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