![]() |
VOOZH | about |
Given an array of strings arr, the task is to return the first palindromic string in the array. If there is no such string, return an empty string "".
Example:
Input: arr = ["abc","car","ada","racecar","cool"]
Output: "ada"
Explanation: The first string that is palindromic is "ada". Note that "racecar" is also palindromic, but it is not the first.Input: arr = ["notapalindrome","racecar"]
Output: "racecar"
Explanation: The first and only string that is palindromic is "racecar".
Approach:
To solve this problem, we need to iterate through each string in the array arr and check if it is a palindrome. A string is a palindrome if it reads the same forwards and backwards. We can do this by comparing the characters from the beginning and the end of the string moving towards the center.
Steps-by-step approach:
Below is the implementation of the above approach:
ada
Time Complexity: O(n*m), where n is the number of strings in the array and m is the average length of the strings. This is because for each string, we check if it is a palindrome in O(m) time.
Auxiliary Space: O(1), as we are using a constant amount of extra space for the palindrome check (ignoring the input space).