VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-first-palindromic-string-in-array/

⇱ Find First Palindromic String in Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find First Palindromic String in Array

Last Updated : 11 Jun, 2024

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:

  • Create a helper function to check if a string is a palindrome.
  • Iterate through each string in the arr array.
    • For each string, use the helper function to check if it is a palindrome.
      • If a palindromic string is found, return it immediately.
      • If no palindromic string is found by the end of the array, return an empty string "".

Below is the implementation of the above approach:


Output
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).

Comment