LeetCode Entry

2108. Find First Palindromic String in the Array

13.02.2024 easy 2024 kotlin rust

Find a palindrome.

2108. Find First Palindromic String in the Array easy blog post substack youtube image.png

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. The eq compares 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())
  }