Problem 2108

Abstract / Summary

Given a list of strings, return the first string that reads the same forwards and backwards.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2108.py

class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        for w in words:
            if w == w[::-1]:
                return w
        return ""
6 lines | 174 bytes | submitted December 27, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method firstPalindrome that receives a list of strings and returns the first element that reads the same forward and backward. If no such element exists, the method returns an empty string. The algorithm proceeds by iterating through the input list once, checking each word for the palindrome property, and exiting immediately when a match is found.

Key Steps

The core logic consists of three distinct operations: iteration over the collection, palindrome verification, and result handling.

for w in words:
    if w == w[::-1]:
        return w

The loop traverses each string w in the input list words. The conditional expression w == w[::-1] determines whether w is identical to its reversed form, which is obtained via Python’s slice notation [::-1]. When the condition holds, the method returns the current word, terminating further processing.

If the loop completes without encountering a palindrome, the method reaches the final statement:

return ""

This provides a defined fallback value when the search yields no result.

Edge Cases Handled

The implementation gracefully addresses several boundary conditions without additional code.

When the input list is empty, the for loop body never executes, and the method proceeds directly to the return "" statement, delivering an empty string as the appropriate response.

If the list contains strings of length zero or one, the slice operation still produces a valid reversed string. A zero-length string equals its reverse, and a single-character string is trivially a palindrome, so the method will correctly identify and return such entries.

In scenarios where none of the supplied words are palindromes, the loop exhausts all elements and the final return supplies an empty string, ensuring a consistent return type.

Performance Optimizations

The algorithm leverages Python’s built-in slicing mechanism to generate the reversed version of each word. This operation is implemented in C under the hood, offering a fast and memory-efficient way to reverse a string compared to manual character swapping.

By returning immediately upon finding the first palindrome, the method avoids unnecessary checks on the remaining elements, achieving an early-exit behavior that reduces the total number of iterations in typical cases where a palindrome appears early in the list.

The linear traversal of the input list means that each word is examined at most once, and the use of direct string comparison (==) benefits from Python’s optimized equality checks, which can short-circuit as soon as a mismatching character is detected.

Overall, the combination of native slice reversal, early exit, and efficient comparison yields a solution that operates with minimal overhead for the problem’s requirements.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big basket full of word blocks. Some of the words look exactly the same if you stand on your head and read them backwards, like the word mom or the word dad. This code acts like a little helper who looks through the basket one word at a time. It picks up the first word and flips it around to see if the letters still match up perfectly with the word it started with. If the word looks the same forwards and backwards, the helper stops searching and pulls that special word out for you to see. If the helper goes through every single word in the basket and still cannot find one that is the same backwards, it simply decides to stop searching and leaves the space empty.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.37 | σ = 0.99

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go C Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
27 links | 14 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   December 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality