#2108
Find First Palindromic String in the Array
EasyArrayTwo PointersStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages a two-pointer technique to check for palindromes in a single pass, which is more efficient than reversing the string.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through each string in the array.
- 2Step 2: For each string, use two pointers to check if the string is a palindrome by comparing characters from both ends towards the center.
- 3Step 3: If a match is found, return that string. If no palindromic string is found by the end of the iteration, return an empty string.
solution.py16 lines
1# Full working Python code
2
3def first_palindromic_string(words):
4 for word in words:
5 if is_palindrome(word):
6 return word
7 return ""
8
9def is_palindrome(s):
10 left, right = 0, len(s) - 1
11 while left < right:
12 if s[left] != s[right]:
13 return False
14 left += 1
15 right -= 1
16 return Trueℹ
Complexity note: The time complexity is O(n) because we only traverse each word once with two pointers, making it more efficient than the brute force method. The space complexity is O(1) since we are not using any additional data structures that grow with input size.
- 1Palindromes can be checked efficiently using two pointers.
- 2The first occurrence is what matters, so we can stop as soon as we find one.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.