forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestElement.java
More file actions
84 lines (77 loc) · 2.71 KB
/
NearestElement.java
File metadata and controls
84 lines (77 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.thealgorithms.datastructures.stacks;
import java.util.Stack;
/**
* The {@code NearestElement} class provides static utility methods to find the
* nearest greater or smaller elements to the left or right of each element in
* an integer array using stack-based algorithms.
*
* <p>
* Each method runs in O(n) time complexity by maintaining a monotonic stack:
* <ul>
* <li>{@code nearestGreaterToRight}: Finds the nearest greater element to the
* right of each element.</li>
* <li>{@code nearestGreaterToLeft}: Finds the nearest greater element to the
* left of each element.</li>
* <li>{@code nearestSmallerToRight}: Finds the nearest smaller element to the
* right of each element.</li>
* <li>{@code nearestSmallerToLeft}: Finds the nearest smaller element to the
* left of each element.</li>
* </ul>
*/
public final class NearestElement {
private NearestElement() {
throw new UnsupportedOperationException("Utility class");
}
public static int[] nearestGreaterToRight(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return result;
}
public static int[] nearestGreaterToLeft(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return result;
}
public static int[] nearestSmallerToRight(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() >= arr[i]) {
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return result;
}
public static int[] nearestSmallerToLeft(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && stack.peek() >= arr[i]) {
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return result;
}
}