LeetCode Entry
2515. Shortest Distance to Target String in a Circular Array
Distance to target
2515. Shortest Distance to Target String in a Circular Array easy substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1329
Problem TLDR
Distance to target #easy
Intuition
- (s+dist)%n forward
- (s-dist)%n backward
Approach
- don’t forget s
- Kotlin has
.modthat handles sign, indexOfFirst vs firstOrNull - Rust:
find
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
// 14ms
fun closestTarget(w: Array<String>, t: String, s: Int) =
w.indices.indexOfFirst { w[(s + it)%w.size]==t || w[(s-it).mod(w.size)]==t }
// 0ms
pub fn closest_target(w: Vec<String>, t: String, s: i32) -> i32 {
let n = w.len() as i32;
(0..n).find(|i| w[((s + i) % n) as usize] == t || w[((s - i + n) % n) as usize] == t).unwrap_or(-1)
}