Skip to content

Commit af85032

Browse files
authored
Refactor MonotonicIncreasingStack for utility class
1 parent 3d026b5 commit af85032

File tree

1 file changed

+12
-20
lines changed

1 file changed

+12
-20
lines changed

src/test/java/com/thealgorithms/stacks/MonotonicIncreasingStack.java

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,51 +7,43 @@
77
import java.util.Arrays;
88
import java.util.Stack;
99

10-
public class MonotonicIncreasingStack
11-
{
10+
public class MonotonicIncreasingStack {
1211

13-
public static int[] nextGreaterElement(int[] arr)
14-
{
12+
private MonotonicIncreasingStack() {
13+
throw new AssertionError("Cannot instantiate utility class");
14+
}
15+
16+
public static int[] nextGreaterElement(int[] arr) {
1517
int n = arr.length;
1618
int[] result = new int[n];
1719
Stack<Integer> stack = new Stack<>();
1820

19-
for (int i = n - 1; i >= 0; i--)
20-
{
21-
while (!stack.isEmpty() && arr[i] >= arr[stack.peek()])
22-
{
21+
for (int i = n - 1; i >= 0; i--) {
22+
while (!stack.isEmpty() && arr[i] >= arr[stack.peek()]) {
2323
stack.pop();
2424
}
25-
2625
result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
2726
stack.push(i);
2827
}
29-
3028
return result;
3129
}
3230

33-
public static int[] nextSmallerElement(int[] arr)
34-
{
31+
public static int[] nextSmallerElement(int[] arr) {
3532
int n = arr.length;
3633
int[] result = new int[n];
3734
Stack<Integer> stack = new Stack<>();
3835

39-
for (int i = n - 1; i >= 0; i--)
40-
{
41-
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()])
42-
{
36+
for (int i = n - 1; i >= 0; i--) {
37+
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
4338
stack.pop();
4439
}
45-
4640
result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
4741
stack.push(i);
4842
}
49-
5043
return result;
5144
}
5245

53-
public static void main(String[] args)
54-
{
46+
public static void main(String[] args) {
5547
int[] arr = {4, 5, 2, 10, 8};
5648

5749
int[] nextGreater = nextGreaterElement(arr);

0 commit comments

Comments
 (0)