Menu

Daily Temperatures: a Monotonic Stack in Rust (Day 25/60)
📰

Daily Temperatures: a Monotonic Stack in Rust (Day 25/60)

DEV Community: rust·Naveen Karasu·1 day ago
#GhlFVdiU
#devtorust#devto#dev#stack#temps
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.