LeetCode Entry

3904. Smallest Stable Index II

05.09.2026 medium 2026 kotlin rust

Index of max suffix - min prefix not less than k

3904. Smallest Stable Index II medium substack youtube

https://dmitrysamoylenko.com/leetcode/

05.09.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1473

Problem TLDR

Index of max suffix - min prefix not less than k

Intuition

Precompute a running minimum suffix.

Approach

  • can be a single expression

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code

    fun firstStableIndex(n: IntArray, k: Int) = n.runningReduce(::maxOf)
        .zip(n.reversed().runningReduce(::minOf).reversed(), Int::minus)
        .indexOfFirst { it <= k }
    pub fn first_stable_index(n: Vec<i32>, k: i32) -> i32 {
        let (mut m, mut x) = (n.clone(), i32::MIN);
        for i in (0..n.len() - 1).rev() { m[i] = m[i].min(m[i + 1]) }
        n.iter().zip(m).position(|(&a, b)| { x = x.max(a); x - b <= k }).map_or(-1, |i| i as _)
    }

Comments