Day 25/60: Daily Temperatures with a Monotonic Stack in Rust
60 Day Rust DSA Challenge
I keep a small weather log for a side project: one temperature reading per day. The question I needed to answer for each day was mundane and turned out to be a perfect monotonic-stack problem -- this is LeetCode 739, Daily Temperatures . For each day, how many days do I wait until a warmer reading? If the temperature never rises again, the answer is 0 .
The version I shipped first, and why it hurt
The obvious solution writes itself. From each day, scan forward until you find a warmer reading:
fn daily_temperatures_naive ( temps : & [ i32 ] ) -> Vec < i32 > { let n = temps . len ( ) ; let mut out = vec! [ 0i32 ; n ] ; for i in 0 . . n { let mut j = i + 1 ; while j < n { if temps [ j ] > temps [ i ] { out [ i ] = ( j - i ) as i32 ; break ; } j += 1 ; } } out }
Enter fullscreen mode
Exit fullscreen mode
It is correct.…