Skip to main content
Back to problems
#2210
Easy Algorithms

Count hills and valleys in an array

Array
69.1% acceptance
Feb 25, 2026
1148
143
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn count_hill_valley(nums: Vec<i32>) -> i32 {
    // Deduplicate consecutive equal elements
    let mut deduped: Vec<i32> = Vec::new();
    for &x in &nums {
      if deduped.last() != Some(&x) {
        deduped.push(x);
      }
    }
    let mut count = 0;
    for i in 1..deduped.len().saturating_sub(1) {
      let (l, c, r) = (deduped[i - 1], deduped[i], deduped[i + 1]);
      if (c > l && c > r) || (c < l && c < r) {
        count += 1;
      }
    }
    count
  }
}