Open In App

Find all Palindrome Strings in given Array of strings

Last Updated : 21 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array.

Examples:

Input: arr[] = {“abc”, “car”, “ada”, “racecar”, “cool”}
Output: “ada”, “racecar”
Explanation: These two are the only palindrome strings in the given array

Input: arr[] = {“def”, “ab”}
Output: -1
Explanation: No palindrome string is present in the given array.

 

Approach: The solution is based on greedy approach. Check every string of an array if it is palindrome or not and also keep track of the all palindrome string. Follow the steps below to solve the problem:

  • Initialize a vector of string ans.
  • Iterate over the range [0, N) using the variable i and If arr[i] is a palindrome, then add it to the ans.
  • After performing the above steps, print the strings present in ans as the resultant strings.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if given string
// is Palindrome or not
bool isPalindrome(string& s)
{
    // Copy string s char into string a
    string a = s;
    reverse(s.begin(), s.end());
 
    // Check if two string are equal or not
    return s == a;
}
 
// Function to return all Palindrome string
vector<string> PalindromicStrings(string arr[],
                                  int N)
{
    vector<string> ans;
 
    // Loop to find palindrome string
    for (int i = 0; i < N; i++) {
 
        // Checking if given string is
        // palindrome or not
        if (isPalindrome(arr[i])) {
 
            // Update answer variable
            ans.push_back(arr[i]);
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
 
    string arr[]
        = { "abc", "car", "ada", "racecar", "cool" };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Print required answer
    vector<string> s = PalindromicStrings(arr, N);
    if(s.size() == 0)
        cout << "-1";
    for(string st: s)
        cout << st << " ";
 
    return 0;
}


Java




// Java code to find the maximum median
// of a sub array having length at least K.
import java.util.*;
public class GFG
{
     
  // Function to check if given string
  // is Palindrome or not
  static boolean isPalindrome(String str)
  {
     
    // Start from leftmost and rightmost corners of str
    int l = 0;
    int h = str.length() - 1;
 
    // Keep comparing characters while they are same
    while (h > l)
    {
      if (str.charAt(l++) != str.charAt(h--))
      {
        return false;
      }
    }
    return true;
  }
 
  // Function to return all Palindrome string
  static ArrayList<String> PalindromicStrings(String []arr,
                                      int N)
  {
    ArrayList<String> ans = new ArrayList<String>();
 
    // Loop to find palindrome string
    for (int i = 0; i < N; i++) {
 
      // Checking if given string is
      // palindrome or not
      if (isPalindrome(arr[i])) {
 
        // Update answer variable
        ans.add(arr[i]);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void main(String args[])
  {
 
    String []arr
      = { "abc", "car", "ada", "racecar", "cool" };
    int N = arr.length;
 
    // Print required answer
    ArrayList<String> s = PalindromicStrings(arr, N);
    if(s.size() == 0)
      System.out.print("-1");
    for (String st : s)
      System.out.print(st + " ");
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




# Python program for the above approach:
 
## Function to check if given string
## is Palindrome or not
def isPalindrome(s):
    ## Copy string s char into string a
    a = ""
    for ch in s:
        a += ch
     
    s = "".join(reversed(s))
 
    ## Check if two string are equal or not
    return s == a
 
## Function to return all Palindrome string
def PalindromicStrings(arr, N):
    ans = []
 
    ## Loop to find palindrome string
    for i in range(N):
 
        ## Checking if given string is
        ## palindrome or not
        if (isPalindrome(arr[i])):
 
            ## Update answer variable
            ans.append(arr[i]);
    return ans
 
## Driver code
if __name__ == '__main__':
    arr = ["abc", "car", "ada", "racecar", "cool" ]
    N = len(arr)
 
    ## Print required answer
    s = PalindromicStrings(arr, N);
    if(len(s) == 0):
        print(-1, end="")
    for st in s:
        print(st, end=" ")
         
        # This code is contributed by subhamgoyal2014.


C#




// C# program for the above approach
using System;
using System.Collections;
class GFG
{
   
  // Function to check if given string
  // is Palindrome or not
  static bool isPalindrome(string str)
  {
     
    // Start from leftmost and rightmost corners of str
    int l = 0;
    int h = str.Length - 1;
 
    // Keep comparing characters while they are same
    while (h > l)
    {
      if (str[l++] != str[h--])
      {
        return false;
      }
    }
    return true;
  }
 
  // Function to return all Palindrome string
  static ArrayList PalindromicStrings(string []arr,
                                      int N)
  {
    ArrayList ans = new ArrayList();
 
    // Loop to find palindrome string
    for (int i = 0; i < N; i++) {
 
      // Checking if given string is
      // palindrome or not
      if (isPalindrome(arr[i])) {
 
        // Update answer variable
        ans.Add(arr[i]);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
 
    string []arr
      = { "abc", "car", "ada", "racecar", "cool" };
    int N = arr.Length;
 
    // Print required answer
    ArrayList s = PalindromicStrings(arr, N);
    if(s.Count == 0)
      Console.Write("-1");
    foreach(string st in s)
      Console.Write(st + " ");
 
  }
}
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
 
// JavaScript code for the above approach
 
 
// Function to check if given string
// is Palindrome or not
function isPalindrome(s)
{
    // Copy string s char into string a
    let a = s;
    s = s.split('').reverse().join('');
 
    // Check if two string are equal or not
    return s == a;
}
 
// Function to return all Palindrome string
function PalindromicStrings(arr,N)
{
    let ans = [];
 
    // Loop to find palindrome string
    for (let i = 0; i < N; i++) {
 
        // Checking if given string is
        // palindrome or not
        if (isPalindrome(arr[i])) {
 
            // Update answer variable
            ans.push(arr[i]);
        }
    }
    return ans;
}
 
// Driver Code
let arr = [ "abc", "car", "ada", "racecar", "cool" ];
let N = arr.length;
 
// Print required answer
let s = PalindromicStrings(arr, N);
if(s.length == 0)
    document.write("-1");
for(let st of s)
    document.write(st," ");
 
// This code is contributed by shinjanpatra
</script>


Output

ada racecar 

 Time complexity: O(N * W) where W is the average length of the strings
Auxiliary Space: O(N * W) 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads