710141. Replace every element with the least greater element on its right
Replace Every Element with the Least Greater Element on Its Right
Summary
This problem is about replacing every element in an array with its least greater element on its right side. The key concept involved is finding the least greater element for each element, which can be achieved using a data structure like an array or binary search tree.
Detailed Explanation
To solve this problem, we will create a stack and iterate over the array from left to right. For each element, we will keep popping elements from the stack until we find one that is greater than our current element. This popped element will be the least greater element on its right side, so we will replace the current element with it.
Here's a step-by-step breakdown of the solution:
- Initialize an empty stack.
- Iterate over the array from left to right.
- For each element, keep popping elements from the stack until you find one that is greater than your current element.
- Replace the current element with the popped element.
- Repeat steps 2-4 for all elements in the array.
Here's an ASCII art diagram illustrating this process:
[1] [2] [3] [4]
| | | |
v v v v
[0] -> [1] -> [2] -> [3] -> [4]
Time complexity: O(n), where n is the size of the array. Space complexity: O(n), as in the worst case, we might need to store all elements in the stack.
Optimized Solutions
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
replaceElements(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void replaceElements(int[] arr) {
Stack<Integer> stack = new Stack<>();
int n = arr.length;
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
}
if (!stack.isEmpty()) {
arr[i] = stack.peek();
} else {
arr[i] = -1;
}
stack.push(arr[i]);
}
}
}