Last active
December 14, 2022 19:29
-
-
Save giuseppe998e/2e64abd696c1c876f7a897aff1c272e2 to your computer and use it in GitHub Desktop.
"Next Greater Element" and "Previous Greater Element" arrays using stack in Rust - Complexity O(n)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn next_greater_elems<T: Copy + PartialOrd>(array: &[T]) -> Box<[Option<T>]> { | |
let array_len = array.len(); | |
let mut stack = Vec::<usize>::with_capacity(array_len); | |
let mut result = Vec::<Option<T>>::with_capacity(array_len); | |
stack.push(0); | |
result.push(None); | |
for (index, element) in array.iter().enumerate().skip(1) { | |
result.push(None); | |
// Use "<=" for "Greater-Equal" | |
while let Some(&stack_index) = stack.last().filter(|&&idx| array[idx] < *element) { | |
result[stack_index] = Some(*element); | |
stack.pop(); | |
} | |
stack.push(index); | |
} | |
result.into_boxed_slice() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn previous_greater_elems<T: Copy + PartialOrd>(array: &[T]) -> Box<[Option<T>]> { | |
let array_len = array.len(); | |
let mut stack = Vec::<usize>::with_capacity(array_len); | |
let mut result = Vec::<Option<T>>::with_capacity(array_len); | |
stack.push(0); | |
result.push(None); | |
for (index, element) in array.iter().enumerate().skip(1) { | |
while stack | |
.last() | |
.filter(|&&idx| array[idx] <= *element) // Use "<" for "Greater-Equal" | |
.is_some() | |
{ | |
stack.pop(); | |
} | |
let result_element = stack.last().map(|&idx| array[idx]); | |
result.push(result_element); | |
stack.push(index); | |
} | |
result.into_boxed_slice() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment