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
102 lines (84 loc) · 2.97 KB
/
NearestElement.java
File metadata and controls
102 lines (84 loc) · 2.97 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.thealgorithms.stacks;
import java.util.Stack;
/**
* Implements classic stack-based algorithms to find nearest elements.
*
* Algorithms included:
* 1. Nearest Greater to Right
* 2. Nearest Greater to Left
* 3. Nearest Smaller to Right
* 4. Nearest Smaller to Left
*/
public final class NearestElement {
// Private constructor to prevent instantiation
private NearestElement() {
}
/** Finds the nearest greater element to the right for each element in the array. */
public static int[] nearestGreaterToRight(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
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;
}
/** Finds the nearest greater element to the left for each element in the array. */
public static int[] nearestGreaterToLeft(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
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;
}
/** Finds the nearest smaller element to the right for each element in the array. */
public static int[] nearestSmallerToRight(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
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;
}
/** Finds the nearest smaller element to the left for each element in the array. */
public static int[] nearestSmallerToLeft(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
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;
}
}