Check if substrings from three given strings can be concatenated to form a palindrome


Palindromes are a fascinating topic in computer science and programming. A palindrome is a word, phrase, number, or other sequences of characters that read the same forward and backward, ignoring spaces, punctuation, and capitalization. In this article, we will investigate a unique problem: how to determine if substrings from three given strings can be concatenated to form a palindrome. This problem is a common interview question and can be solved using various techniques, including string manipulation, hashing, and dynamic programming.

Problem Statement

Given three strings, the task is to check if it's possible to select substrings from each of the given strings and concatenate them to form a palindrome.

Approach

The general approach to solve this problem includes the following steps −

  • Concatenate the three strings in six different ways (all permutations of the three strings).

  • For each concatenated string, check if it can form a palindrome.

To check if a string can form a palindrome, we need to ensure that no more than one character has an odd frequency in the string.

C++ Solution

Example

Here's the C++ function that implements the above approach −

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// Function to check if a given string can form a palindrome
bool canFormPalindrome(const char *s) {
   int count[256] = {0};  // Array to store character frequency
   for (const char *p = s; *p != '\0'; p++) {
      count[(int)*p]++;
   }
   int odd = 0;  // Count of characters with odd frequency
   for (int i = 0; i < 256; i++) {
      if (count[i] & 1) {  // Check for odd frequency
         odd++;
      }
      if (odd > 1) {  // If more than one character has odd frequency, palindrome is not possible
         return false;
      }
   }
   return true;  // Palindrome can be formed
}

bool checkSubstrings(const char *s1, const char *s2, const char *s3) {
   const char *arr[] = {s1, s2, s3, s1, s3, s2};  // Array of strings combinations
   for (int i = 0; i < 3; i++) {
      char concatenated[16];
      strcpy(concatenated, arr[i]);
      strcat(concatenated, arr[i + 1]);
      strcat(concatenated, arr[i + 2]);
      if (canFormPalindrome(concatenated)) {
         return true;  // Palindromic substring combination found
      }
   }
   return false;  // No palindromic substring combination found
}
int main() {
   const char *s1 = "abc";
   const char *s2 = "def";
   const char *s3 = "cba";
   if (checkSubstrings(s1, s2, s3)) {
      printf("Yes\n");
   } else {
      printf("No\n");
   }
   return 0;
}

Output

No
#include<bits/stdc++.h>
using namespace std;

bool canFormPalindrome(string str) {
   vector<int> count(256, 0);
   for (int i = 0; str[i]; i++)
      count[str[i]]++;
   int odd = 0;
   for (int i = 0; i < 256; i++) {
      if (count[i] & 1)
         odd++;
      if (odd > 1)
         return false;
   }
   return true;
}

bool checkSubstrings(string s1, string s2, string s3) {
   string arr[] = {s1, s2, s3, s1, s3, s2};
   for (int i = 0; i < 3; i++) {
      if (canFormPalindrome(arr[i] + arr[i + 1] + arr[i + 2]))
      return true;
   }
   return false;
}

int main() {
   string s1 = "abc";
   string s2 = "def";
   string s3 = "cba";
   if (checkSubstrings(s1, s2, s3))
      cout << "Yes\n";
   else
      cout << "No\n";
   return 0;
}

Output

No
public class PalindromeSubstrings {
   public static boolean canFormPalindrome(String str) {
      int[] count = new int[256];  // Array to store character frequency
      for (char c : str.toCharArray()) {
         count[c]++;  // Count characters in the string
      }
      int odd = 0;  // Count of characters with odd frequency
      for (int c : count) {
         if ((c & 1) == 1) {  
            odd++;
         }
         if (odd > 1) {  // If more than one character has odd frequency, palindrome is not possible
            return false;
         }
      }
      return true;  
   }

   public static boolean checkSubstrings(String s1, String s2, String s3) {
      String[] arr = {s1, s2, s3, s1, s3, s2};  // Array of strings combinations
      for (int i = 0; i < 3; i++) {
         if (canFormPalindrome(arr[i] + arr[i + 1] + arr[i + 2])) {
            return true;  // Palindromic substring combination found
         }
      }
      return false;  // No palindromic substring combination found
   }

   public static void main(String[] args) {
      String s1 = "abc";
      String s2 = "def";
      String s3 = "cba";
      if (checkSubstrings(s1, s2, s3)) {
         System.out.println("Yes");
      } else {
         System.out.println("No");
      }
   }
}

Output

No
def can_form_palindrome(s):
   count = [0] * 256  # List to store character frequency
   for c in s:
      count[ord(c)] += 1  # Count characters in the string
   odd = 0  # Count of characters with odd frequency
   for c in count:
      if c & 1:  # Check for odd frequency
         odd += 1
      if odd > 1:  # If more than one character has odd frequency, palindrome is not possible
         return False
   return True 

def check_substrings(s1, s2, s3):
   arr = [s1, s2, s3, s1, s3, s2]  # List of strings combinations
   for i in range(3):
      if can_form_palindrome(arr[i] + arr[i + 1] + arr[i + 2]):
         return True  # Palindromic substring combination found
   return False  # No palindromic substring combination found

def main():
   s1 = "abc"
   s2 = "def"
   s3 = "cba"
   if check_substrings(s1, s2, s3):
      print("Yes")
   else:
      print("No")

if __name__ == "__main__":
   main()

Output

No

Example Test Case Explanation

Let's take the strings as "abc", "def", and "cba".

The function canFormPalindrome(str) checks if the entire string can be rearranged to form a palindrome, not whether it is already a palindrome.

With the strings "abc", "de", and "edcba", the concatenation "abcdeedcba" cannot be rearranged to form a palindrome because there are two 'd' characters and two 'e' characters, but there is only one 'b' character. Therefore, the output is indeed "No".

The function checkSubstrings checks all possible concatenations of the three strings. However, none of these can be rearranged to form a palindrome, so the output is "No".

Conclusion

Being able to solve such problems not only helps in acing coding interviews but also enhances problem-solving skills, which are essential for every software engineer. This problem is a good example of how to use string manipulation and hashing to solve complex problems. Practice and understanding are key to mastering these topics.

Updated on: 16-Oct-2023

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements