Find First Palindromic String in the Array — LeetCode 2108 Python Solution

EasyArrayTwo PointersString
Problem
#2108
Reading time
2 min

The problem

Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".

Example

Input
words = ["abc","car","ada","racecar","cool"]
Output
"ada"
Explanation
The first string that is palindromic is "ada".

Python solution

Python
class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        return next((w for w in words if w == w[::-1]), "")

Complexity

MeasureComplexity
TimeO(L), where L is the sum of the lengths of all strings in the array `words`
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2108. Find First Palindromic String in the Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2108. Find First Palindromic String in the Array?
LeetCode 2108. Find First Palindromic String in the Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2108. Find First Palindromic String in the Array?
The Python solution on this page runs in O(L), where L is the sum of the lengths of all strings in the array `words`.
What is the space complexity of LeetCode 2108. Find First Palindromic String in the Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2108. Find First Palindromic String in the Array cover?
LeetCode 2108. Find First Palindromic String in the Array is tagged Array, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview