Open In App

Palindrome check for concatenation of Prefixes and Suffixes

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N and an array of strings arr[], the task is to check whether the concatenation of prefixes and suffixes of all strings forms a palindrome or not. 

Examples: 

Input: N = 4, arr[] = {“bcd”, “cd”, “a”, “d”, “abc”, “ab”}
Output: No
Explanation: “a”, “ab” and “abc” are prefixes. “d”, “cd” and “bcd” are suffixes. So the final string is “abcd” which is not a palindrome.

and

Input: N = 3, arr[] = {“i”, “io”, “i”, “oi”} 
Output: Yes
Explanation: “i” and “io” are prefixes. “i” and “oi” are suffixes. The final string is “ioi” which is a palindrome.

Approach: This can be solved with the following idea:

If we have a string s of length N and we know that there are exactly two strings of length N – 1 (one prefix and one suffix), which we will call x and y, then we can determine whether s is a palindrome by checking if the reversal of x is equal to y. In other words, if s is a palindrome, then the prefix x and suffix y must be the same string when read in reverse order. Conversely, if the prefix and suffix are the same when read in reverse order, then s is a palindrome.

Below are the steps involved in the implementation of the code:

  • Define the palindrome function that takes two strings a and b as input and returns a Boolean value indicating whether the two strings can be concatenated to form a palindrome of length 2*n-2.
  • Define the solve function that takes a vector of strings arr and an integer n as input.
  • Use a loop to iterate through all strings in the input array arr[]. For each iteration, check whether the length of the string is n-1. If it is, add the string to the vector v.
  • Call the palindrome function with the first two strings in the vector v. If the function returns true, print “YES” and return.
  • If the function returns false, call the palindrome function with the second and first string in the vector v. If the function returns true, print “YES” and return.
  • If both calls to the palindrome function return false, print “NO“.

Below is the implementation for the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether two strings
// can be concatenated to form a
// palindrome of length 2*n-2
bool palindrome(string a, string b)
{
    int n = a.size();
 
    // If the first character of a does
    // not match the last character of b,
    // return false
    if (a[0] != b[n - 1])
        return 0;
    for (int i = 1, j = n - 2; i < n, j >= 0; i++, j--) {
 
        // If any corresponding characters
        // don't match, return false
        if (a[i] != b[j])
            return 0;
    }
 
    // If all characters match,
    // return true
    return 1;
}
 
// Function to solve the problem
void solve(vector<string> arr, int n)
{
    vector<string> v;
 
    // Loop through all strings in the
    // input array and identify the two
    // strings of length n-1
    for (int i = 0; i < 2 * n - 2; i++) {
        if (arr[i].size() == n - 1)
 
            // Add the string to the
            // vector v
            v.push_back(arr[i]);
    }
 
    // Check whether the two strings in v
    // can be concatenated to form a
    // palindrome
    if (palindrome(v[0], v[1]) || palindrome(v[1], v[0]))
 
        // If yes, print "YES"
        cout << "YES" << endl;
    else
        // If no, print "NO"
        cout << "NO" << endl;
}
 
// Driver code
int main()
{
    int n = 6;
    vector<string> arr
        = { "ltw", "ti", "l", "ltwp", "i",
            "lt", "wpti", "pti", "ltwpt", "twpti" };
 
    // Function call
    solve(arr, n);
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
class GFG {
    // Function to check whether two strings
    // can be concatenated to form a
    // palindrome of length 2*n-2
    static boolean palindrome(String a, String b) {
        int n = a.length();
 
        // If the first character of a does
        // not match the last character of b,
        // return false
        if (a.charAt(0) != b.charAt(n - 1))
            return false;
 
        for (int i = 1, j = n - 2; i < n && j >= 0; i++, j--) {
            // If any corresponding characters
            // don't match, return false
            if (a.charAt(i) != b.charAt(j))
                return false;
        }
 
        // If all characters match,
        // return true
        return true;
    }
    // Nikunj Sonigara
    // Function to solve the problem
    static void solve(List<String> arr, int n) {
        List<String> v = new ArrayList<>();
 
        // Loop through all strings in the
        // input array and identify the two
        // strings of length n-1
        for (int i = 0; i < 2 * n - 2; i++) {
            if (arr.get(i).length() == n - 1) {
                // Add the string to the
                // list v
                v.add(arr.get(i));
            }
        }
 
        // Check whether the two strings in v
        // can be concatenated to form a
        // palindrome
        if (palindrome(v.get(0), v.get(1)) || palindrome(v.get(1), v.get(0))) {
            // If yes, print "YES"
            System.out.println("YES");
        } else {
            // If no, print "NO"
            System.out.println("NO");
        }
    }
 
    public static void main(String[] args) {
        int n = 6;
        List<String> arr = List.of("ltw", "ti", "l", "ltwp", "i", "lt", "wpti", "pti", "ltwpt", "twpti");
 
        // Function call
        solve(arr, n);
    }
}


Python3




def palindrome(a, b):
    n = len(a)
     
    # If the first character of a does
    # not match the last character of b,
    # return False
    if a[0] != b[n-1]:
        return False
     
    for i in range(1, n):
        j = n - i - 1
         
        # If any corresponding characters
        # don't match, return False
        if a[i] != b[j]:
            return False
     
    # If all characters match,
    # return True
    return True
 
# Nikunj Sonigara
def solve(arr, n):
    v = []
     
    # Loop through all strings in the
    # input array and identify the two
    # strings of length n-1
    for i in range(2*n-2):
        if len(arr[i]) == n - 1:
            # Add the string to the list v
            v.append(arr[i])
     
    # Check whether the two strings in v
    # can be concatenated to form a palindrome
    if palindrome(v[0], v[1]) or palindrome(v[1], v[0]):
        # If yes, print "YES"
        print("YES")
    else:
        # If no, print "NO"
        print("NO")
 
# Driver code
n = 6
arr = ["ltw", "ti", "l", "ltwp", "i", "lt", "wpti", "pti", "ltwpt", "twpti"]
 
# Function call
solve(arr, n)


C#




// C# code for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to check whether two strings
    // can be concatenated to form a
    // palindrome of length 2*n-2
    static bool Palindrome(string a, string b)
    {
        int n = a.Length;
 
        // If the first character of a does
        // not match the last character of b,
        // return false
        if (a[0] != b[n - 1])
            return false;
 
        for (int i = 1, j = n - 2; i < n && j >= 0; i++, j--)
        {
            // If any corresponding characters
            // don't match, return false
            if (a[i] != b[j])
                return false;
        }
 
        // If all characters match,
        // return true
        return true;
    }
 
    // Nikunj Sonigara
    // Function to solve the problem
    static void Solve(List<string> arr, int n)
    {
        List<string> v = new List<string>();
 
        // Loop through all strings in the
        // input array and identify the two
        // strings of length n-1
        for (int i = 0; i < 2 * n - 2; i++)
        {
            if (arr[i].Length == n - 1)
            {
                // Add the string to the
                // list v
                v.Add(arr[i]);
            }
        }
 
        // Check whether the two strings in v
        // can be concatenated to form a
        // palindrome
        if (Palindrome(v[0], v[1]) || Palindrome(v[1], v[0]))
        {
            // If yes, print "YES"
            Console.WriteLine("YES");
        }
        else
        {
            // If no, print "NO"
            Console.WriteLine("NO");
        }
    }
 
    static void Main(string[] args)
    {
        int n = 6;
        List<string> arr = new List<string> { "ltw", "ti", "l", "ltwp", "i", "lt", "wpti", "pti", "ltwpt", "twpti" };
 
        // Function call
        Solve(arr, n);
    }
}


Javascript




// Define a function to check if two strings are palindromes when concatenated
function palindrome(a, b) {
    const n = a.length;
 
    // Check if the first character of 'a' matches the last character of 'b'
    if (a[0] !== b[n - 1])
        return false;
 
    // Check the remaining characters in 'a' and 'b' to see if they form palindromes
    for (let i = 1, j = n - 2; i < n && j >= 0; i++, j--) {
        if (a[i] !== b[j])
            return false;
    }
 
    // If the conditions for a palindrome are met, return true
    return true;
}
 
// Define a function to solve the problem
function solve(arr, n) {
    const v = [];
 
    // Loop through the array 'arr' and select strings of length 'n - 1'
    for (let i = 0; i < 2 * n - 2; i++) {
        if (arr[i].length === n - 1)
            v.push(arr[i]);
    }
 
    // Check if the first two selected strings form a palindrome when concatenated in both orders
    if (palindrome(v[0], v[1]) || palindrome(v[1], v[0]))
        console.log("YES");
    else
        console.log("NO");
}
 
// Define the value of 'n' and the array 'arr'
const n = 6;
const arr = [
    "ltw", "ti", "l", "ltwp", "i",
    "lt", "wpti", "pti", "ltwpt", "twpti"
];
 
// Call the 'solve' function to solve the problem
solve(arr, n);


Output

NO







Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads