![]() |
VOOZH | about |
Given an array arr[] consisting of n strings. The task is to find if there exists a pair of indices (i, j) such that i ≠ j and the concatenation arr[i] + arr[j] forms a palindrome.
Return true if such a pair exists; otherwise, return false.
Note: A string is considered a palindrome if it reads the same forward and backward.
Examples:
Input: arr[] = ["geekf", "geeks", "or", "keeg", "abc", "bc"]
Output: true
Explanation: Strings "geekf" and "keeg" can be concatenated to form a palindromic string "geekfkeeg" .Input: arr[] = ["abc", "xyxcba", "geekst", "or", "keeg", "bc"]
Output: true
Explanation: Strings "abc" and "xyxcba" can be concatenated to form a palindromic string "abcxyxcba" .Input: arr[] = ["abc", "ab", "xyz"]
Output: false
Explanation: No palindromic string can be formed by concatenating any two of the given strings.
Table of Content
The idea is to iteratively generate all possible pairs of strings using the nested loops and check if any of them is a palindrome.
Dry run for arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"]:
Final answer : True
True
Time Complexity: O(n2 * k), here n is the number of words in the array arr[] and k is the length of the longest concatenated string.
Auxiliary Space: O(1)
The idea is to use Trie Data Structure to store all the strings and efficiently search for palindromic pairs. The intuition behind the Trie approach is to efficiently match each word with the reverse of another word to form a palindrome, without checking all pairs. We insert all words in reversed form into a Trie, while also storing information about prefixes that are palindromes. Then, for each word, we traverse the Trie to see if it can match with a reversed word such that the remaining part of the word forms a palindrome.
True
The above approach can also be implemented using HashMap instead of Trie. The intuition behind this approach is to break each word into two parts (a prefix and a suffix) and try to form a palindrome by pairing it with another word. For every split, we check two cases: if the prefix is a palindrome, then we look for the reverse of the suffix in the array; and if the suffix is a palindrome, we look for the reverse of the prefix. If such a matching word exists, combining them will form a palindrome.
Dry run for arr = ["geekf", "geeks", "keeg"]:
"geekf"Final answer : True
True