Python 2108.py
class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for w in words:
if w == w[::-1]:
return w
return ""
Difficulty
and has an acceptance rate of about 84% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- String
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 125: Valid Palindrome
Solved On The Same Day
- problem 1812: Determine Color of a Chessboard Square
- problem 2119: A Number After a Double Reversal
- problem 2778: Sum of Squares of Special Elements
- problem 2326: Spiral Matrix IV
Extra
- 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