fn next_greater_element(nums: Vec<i32>) -> Vec<i32> {
let mut stack = Vec::new();
let mut result = vec![-1; nums.len()];
for i in 0..nums.len() {
while let Some(&top) = stack.last() {
if nums[i] > nums[top] {
result[top] = nums[i];
stack.pop();
} else {
break;
}
}
stack.push(i);
}
result
}
fn main() {
let nums = vec![4, 5, 2, 25];
let res = next_greater_element(nums);
println!("{:?}", res);
}The code uses a stack to track indexes of elements for which the next greater element is not found yet. When a bigger element is found, it updates the result for those indexes. For the input [4, 5, 2, 25], the next greater elements are [5, 25, 25, -1].
fn next_greater_element(nums: Vec<i32>) -> Vec<i32> {
let mut stack = Vec::new();
let mut result = vec![-1; nums.len()];
for i in 0..nums.len() {
while let Some(&top) = stack.last() {
if nums[i] > nums[top] {
result[top] = nums[i];
stack.pop();
} else {
break;
}
}
stack.push(i);
}
result
}
fn main() {
let nums = vec![9, 7, 5, 3];
let res = next_greater_element(nums);
println!("{:?}", res);
}Since the array is strictly descending, no element has a next greater element to its right. So all values remain -1.
fn next_greater_element(nums: Vec<i32>) -> Vec<i32> {
let mut stack = Vec::new();
let mut result = vec![-1; nums.len()];
for i in 0..nums.len() {
while let Some(top) = stack.last() {
if nums[i] > nums[*top] {
result[*top] = nums[i];
stack.pop();
} else {
break;
}
}
stack.push(i);
}
result
}
fn main() {
let nums = vec![2, 1, 3];
let res = next_greater_element(nums);
println!("{:?}", res);
}The code tries to move the value out of a reference when using while let Some(top) = stack.last(). This causes a compilation error because stack.last() returns a reference and the code tries to move it.
fn next_greater_element_circular(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut result = vec![-1; n];
let mut stack = Vec::new();
for i in 0..(2 * n) {
let idx = i % n;
while let Some(&top) = stack.last() {
if nums[idx] > nums[top] {
result[top] = nums[idx];
stack.pop();
} else {
break;
}
}
if i < n {
stack.push(idx);
}
}
result
}
fn main() {
let nums = vec![1, 2, 1];
let res = next_greater_element_circular(nums);
println!("{:?}", res);
}The circular logic allows the last element to find the next greater element at the start of the array. For [1, 2, 1], the next greater elements are [2, -1, 2].
Each element is pushed onto the stack once and popped at most once, so the total operations are proportional to n, making the time complexity O(n).
