Given three strings S1, S2, and S3 of lengths L, M, and N respectively, the task is to check if it is possible to choose some non-empty substrings from S1, S2, and S3 such that their concatenation is a palindrome. If found to be true, print “YES”. Otherwise, print “NO”.
Input: S1 = “adcb”, S2 = “bcdb”, S3 = “dce”
One of the possible ways is as follows:
Select substring “ad” from the string S1, “d” from the string S2, and “a” from the string S3. Therefore, the resultant string is S = “adda”, which is a palindrome. Therefore, the output should be “YES”.
Input: S1 = “a”, S2 = “bc”, S3 = “c”
Approach: The idea is to observe that it is always possible to find such a, b, and c such that a+b+c becomes palindrome if S1 and S3 have at least one common character. Follow the below steps to solve the problem:
- Initialize two variables, say maskA and maskC, for masking the characters in the strings S1 and S3 respectively.
- Iterate over the characters of the string S1 and set (i-‘a’)th bit in maskA, indicating that the respective character is present in string S1.
- Iterate over characters of the string S3 and set (i-‘a’)th bit in maskC, indicating that the respective character is present in string S3.
- If the Bitwise AND of maskA and maskC is greater than zero, then print “YES”. Otherwise, print “NO”.
Below is the implementation of the above approach:
Time Complexity: O(L + N)
Auxiliary Space: O(L + M + N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.