Open In App

Find Last Palindrome String in the given Array

Last Updated : 19 Jan, 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 return the last palindromic string in the array. 

Note: It guarantees that always one palindromic string is present.

Examples:

Input: arr[] = {“abc”, “car”, “ada”, “racecar”, “cool”}
Output: “racecar”
Explanation: The Last string that is palindromic is “racecar”. 
Note that “ada” is also palindromic, but it is not the Last.

Input: arr[] = {“def”, “aba”}
Output: “aba”

 

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

  • Initialize a string variable ans as an empty string.
  • Iterate over the range (N, 0] using the variable i and perform the following tasks:
    • If arr[i] is a palindrome, then set the value of ans as arr[i].
  • After performing the above steps, print the value of ans as the answer.

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 last Palindrome string
string LastPalindrome(string arr[], int N)
{
 
    // Loop to find the last palindrome string
    for (int i = N - 1; i >= 0; i--) {
 
        // Checking if given string is
        // palindrome or not
        if (isPalindrome(arr[i])) {
 
            // Return the answer
            return arr[i];
        }
    }
}
 
// Driver Code
int main()
{
 
    string arr[]
        = { "abc", "car", "ada", "racecar",
            "cool" };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Print required answer
    cout << LastPalindrome(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
class GFG {
 
  // Function to check if given string
  // is Palindrome or not
  static boolean isPalindrome(String s)
  {
 
    // Copy string s char into string a
    String a = s;
    a = new StringBuffer(a).reverse().toString();
 
    // Check if two string are equal or not
    return s.equals(a);
  }
 
  // Function to return last Palindrome string
  static String LastPalindrome(String arr[], int N) {
 
    // Loop to find the last palindrome string
    for (int i = N - 1; i >= 0; i--) {
 
      // Checking if given string is
      // palindrome or not
      if (isPalindrome(arr[i])) {
 
        // Return the answer
        return arr[i];
      }
    }
    return "Hi";
  }
 
  // Driver Code
  public static void main(String args[]) {
 
    String arr[] = { "abc", "car", "ada", "racecar", "cool" };
    int N = arr.length;
 
    // Print required answer
    System.out.println(LastPalindrome(arr, N));
  }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python code for the above approach
 
# Function to check if given string
# is Palindrome or not
def isPalindrome(s):
 
    # find the length of a string
    _len = len(s)
    for i in range(_len // 2):
 
        # check if first and last string are same
        if s[i] != s[_len - 1 - i]:
            return 0
    return 1
 
# Function to return last Palindrome string
def LastPalindrome(arr, N):
 
    # Loop to find the last palindrome string
    for i in range(N - 1, 0, -1):
 
        # Checking if given string is
        # palindrome or not
        if isPalindrome(arr[i]):
 
            # Return the answer
            return arr[i]
 
# Driver Code
arr = ["abc", "car", "ada", "racecar", "cool"]
N = len(arr)
 
# Print required answer
print(LastPalindrome(arr, N))
 
# This code is contributed by gfgking


C#




// C# program for the above approach
using System;
 
class GFG {
 
  // Function to check if given string
  // is Palindrome or not
  static bool isPalindrome(string s)
  {
 
    // Copy string s char into string a
    char[] a = s.ToCharArray();
    Array.Reverse(a);
    string p  = new string(a);
    //a = new StringBuffer(a).reverse().toString();
 
    // Check if two string are equal or not
    return s.Equals(p);
  }
 
  // Function to return last Palindrome string
  static string LastPalindrome(string[] arr, int N) {
 
    // Loop to find the last palindrome string
    for (int i = N - 1; i >= 0; i--) {
 
      // Checking if given string is
      // palindrome or not
      if (isPalindrome(arr[i])) {
 
        // Return the answer
        return arr[i];
      }
    }
    return "Hi";
  }
 
  // Driver Code
  public static void Main() {
 
    string []arr = { "abc", "car", "ada", "racecar", "cool" };
    int N = arr.Length;
 
    // Print required answer
    Console.Write(LastPalindrome(arr, N));
  }
}
 
// This code is contributed by ukasp.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to check if given string
       // is Palindrome or not
       function isPalindrome(s)
       {
        
           // find the length of a string
           let len = s.length;
           for (let i = 0; i < len / 2; i++)
           {
 
               // check if first and last string are same
               if (s[i] !== s[len - 1 - i]) {
                   return 0;
               }
           }
           return 1;
       }
 
       // Function to return last Palindrome string
       function LastPalindrome(arr, N) {
 
           // Loop to find the last palindrome string
           for (let i = N - 1; i >= 0; i--) {
 
               // Checking if given string is
               // palindrome or not
               if (isPalindrome(arr[i])) {
 
                   // Return the answer
                   return arr[i];
               }
           }
       }
 
       // Driver Code
       let arr = ["abc", "car", "ada", "racecar",
               "cool"];
       let N = arr.length;
 
       // Print required answer
       document.write(LastPalindrome(arr, N));
 
 // This code is contributed by Potta Lokesh
   </script>


 
 

Output: 

racecar

 

Time Complexity: O(N*W) where W is the maximum size of any string in arr[]
Auxiliary Space: O(1) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads