LeetCode Entry
2108. Find First Palindromic String in the Array
Find a palindrome.
2108. Find First Palindromic String in the Array easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/504
Problem TLDR
Find a palindrome.
Intuition
Compare first chars with the last.
Approach
Let’s use some API’s:
- Kotlin:
firstOrNull,all - Rust:
into_iter,find,chars,eq,rev,unwrap_or_else,into. Theeqcompares two iterators with O(1) space.
Complexity
-
Time complexity: \(O(wn)\)
-
Space complexity: \(O(1)\)
Code
fun firstPalindrome(words: Array<String>) =
words.firstOrNull { w ->
(0..w.length / 2).all { w[it] == w[w.lastIndex - it] }
} ?: ""
pub fn first_palindrome(words: Vec<String>) -> String {
words.into_iter().find(|w|
w.chars().eq(w.chars().rev())
).unwrap_or_else(|| "".into())
}