Forming the Longest Palindrome by Concatenating Array Strings
Given an array of X strings in which each string consists of two lowercase English letters, join as many strings together as possible in order to obtain a palindrome.
Input: arr = [“ck”, “kc”, “ho”, “kc”] Output: 4
explanation being that the longest palindrome are “ckkc” and “kcck” which both have lengths of 4.
Google phone screen question.
Problem Explanation
You have an array of strings, each containing exactly two lowercase letters. You can concatenate these strings in any order to create a longer string. The goal is to form the longest palindrome possible. The length of this palindrome is the output.
Key Insights
- A palindrome reads the same forward and backward.
- For each string, its reverse must also exist in the array to form a palindrome.
Approach
Initialize Count: Start with a variable
count
set to 0. This variable will hold the length of the longest palindrome.Hash Table: Create a hash table (dictionary) to store the frequency of each string in the array.
Find Pairs: For each string in the array, check if its reverse exists in the hash table.
- If it exists, you can form a palindrome with these two strings. Remove both strings from the hash table and add 4 to
count
.
- Check Remaining Strings: Some strings may still be left in the hash table. They can’t form a palindrome with any other string, but if they are palindromes themselves, one of them can be placed in the middle of the final string to increase the length by 2.
- Check if any string is a palindrome. If yes, add 2 to
count
.
- Return Count: The value in
count
is the length of the longest palindrome that can be formed. Return this value.
Code
Python code:
|
|
Test the Function
|
|
This function should solve the problem efficiently.