#2058
Medium Algorithms Find the minimum and maximum number of nodes between critical points
Linked List
69.5% acceptance
Feb 25, 2026
1393
73
A critical point in a linked list is defined as either a local maxima or a local minima.
A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.
A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.
Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.
Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn nodes_between_critical_points(head: Option<Box<ListNode>>) -> Vec<i32> {
let mut vals = vec![];
let mut cur = &head;
while let Some(node) = cur {
vals.push(node.val);
cur = &node.next;
}
let n = vals.len();
let mut criticals = vec![];
for i in 1..n - 1 {
if (vals[i] > vals[i - 1] && vals[i] > vals[i + 1])
|| (vals[i] < vals[i - 1] && vals[i] < vals[i + 1])
{
criticals.push(i as i32);
}
}
if criticals.len() < 2 {
return vec![-1, -1];
}
let max_dist = criticals.last().unwrap() - criticals[0];
let min_dist = criticals.windows(2).map(|w| w[1] - w[0]).min().unwrap();
vec![min_dist, max_dist]
}
}