NeetCode #187LC-2108EasyTwo Pointers
← Back to All Problems#187 · #2108 · Find First Palindromic String in the Array(找出数组中的第一个回文字符串)
📌 Problem Statement & Constraints
Given an array of strings
words, return the first palindromic string. If there is no such string, return an empty string. Constraints: 1 <= words.length <= 100, 1 <= words[i].length <= 100.💡 Core Algorithmic Approaches
- Iterate the array in order and test each word for palindromicity.
- The first word that is a palindrome is the answer.
- A palindrome test is a two-pointer scan from the ends, or the slice comparison
w == w[::-1]. - Return the empty string if none qualifies.
💻 Benchmark Python3 Implementation
class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for w in words:
if w == w[::-1]: # slice comparison is O(len(w))
return w
return ""⚡ Complexity Deep Dive
⏱️ Time Complexity
O(total characters in the worst case): each word is tested once with a linear palindrome check.
💾 Space Complexity
O(len(w)) for the reversed slice of the current word (O(1) extra if a two-pointer check is used instead).
⚠️ Interview Pitfalls & Follow-ups
- Returning
None: the contract requires an empty string. - Testing only the first and last characters: a full check is needed.
- Sorting or scanning for the longest palindrome: the requirement is the first in input order.
- Using a two-pointer check to save the slice allocation: a valid micro-optimisation, but the slice version is clearer and the constraints are tiny.