Sponsored
Sponsored
This approach involves checking each string using a two-pointer technique. You set one pointer at the start and one at the end of the string and compare characters. If all characters match until the pointers cross, the string is a palindrome.
Time Complexity: O(n * m), where n is the number of words and m is the average length of the words.
Space Complexity: O(1) because it uses constant space.
1def is_palindrome(s):
2 return s == s[::-1]
3
4def first_palindrome(words):
5 for word in words:
6 if is_palindrome(word):
7 return word
8 return ""
The function is_palindrome
checks if a string is a palindrome by comparing it to its reverse. The first_palindrome
function iterates through the list to locate and return the first palindromic string found.
This method leverages string reversal to check if a word is a palindrome. You can reverse the string and compare it with the original; if they are the same, it's a palindrome.
Time Complexity: O(n * m), where n is the number of words and m is the length of words.
Space Complexity: O(m) due to the additional string for reversal.
1
The reverse
function creates and returns a reversed version of the input string. In firstPalindrome
, for each word in the array, it checks if the word equals its reversed counterpart, indicating it's a palindrome, and returns it.