LeetCode Entry
1848. Minimum Distance to the Target Element
Distance to target from start
1848. Minimum Distance to the Target Element easy substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1327
Problem TLDR
Distance to target from start #easy
Intuition
Iterate from left to right. Or iterate from the start.
Approach
- Kotlin ‘zip’ doesn’t work with non-equal ranges
- Rust itertools has ‘interleave’, abs_diff
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
// 16ms
fun getMinDistance(n: IntArray, t: Int, s: Int) =
n.indices.filter { n[it] == t }.minOf { abs(it - s) }
// 0ms
pub fn get_min_distance(n: Vec<i32>, t: i32, s: i32) -> i32 {
(0..=s as usize).rev().interleave(s as usize+1..n.len())
.find(|&i| n[i] == t).unwrap().abs_diff(s as usize) as _
}