Skip to main content
Back to problems
#3751
Medium Algorithms

Total waviness of numbers in range i

Math Dynamic Programming Enumeration
80.5% acceptance
Feb 25, 2026
46
3
You are given two integers num1 and num2 representing an inclusive range [num1, num2]. The waviness of a number is defined as the total count of its peaks and valleys: A digit is a peak if it is strictly greater than both of its immediate neighbors. A digit is a valley if it is strictly less than both of its immediate neighbors. The first and last digits of a number cannot be peaks or valleys. Any number with fewer than 3 digits has a waviness of 0. Return the total sum of waviness for all numbers in the range [num1, num2].

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn total_waviness(num1: i32, num2: i32) -> i32 {
    let waviness = |n: i32| -> i32 {
      let s: Vec<i32> = n.to_string().bytes().map(|b| (b - b'0') as i32).collect();
      let m = s.len();
      if m < 3 { return 0; }
      (1..m - 1).filter(|&i| {
        (s[i] > s[i-1] && s[i] > s[i+1]) || (s[i] < s[i-1] && s[i] < s[i+1])
      }).count() as i32
    };
    (num1..=num2).map(waviness).sum()
  }
}