Similar Problems

Similar Problems not available

Longest Palindrome By Concatenating Two Letter Words - Leetcode Solution

Companies:

LeetCode:  Longest Palindrome By Concatenating Two Letter Words Leetcode Solution

Difficulty: Medium

Topics: greedy hash-table string array  

The problem Longest Palindrome By Concatenating Two Letter Words on Leetcode is as follows:

Given a list of words, find the longest palindrome that can be formed by concatenating any two words.

Example 1:

Input: ["abcd","dcba","lls","s","sssll"] Output: "slls" Explanation: "dcbaabcd" can also be used to form the longest palindrome "abcddcba", but "slls" is lexicographically smaller.

Example 2:

Input: ["bat","tab","cat"] Output: "batcat" Explanation: The palindrome "battab" is not included in the output because it is not a concatenation of two words.

To solve this problem, we can use a two-pointer approach. We first sort the words list in lexicographical order. Then, we iterate through each pair of words and check if their concatenation is a palindrome. If it is, we update our longest palindrome variable.

Here is the detailed solution:

  1. Sort the input words list in lexicographical order.

  2. Initialize a variable called longest_palindrome to an empty string.

  3. Iterate through each pair of words using two nested loops. The outer loop ranges from the first word to the second last word and the inner loop ranges from the next word to the last word.

  4. Concatenate the two words and check if the resulting string is a palindrome by comparing it with its reverse. If it is a palindrome, update the longest_palindrome variable if its length is greater than the current value.

  5. Return the longest_palindrome variable at the end of the iteration.

Here is the Python code implementing this solution:

def longestPalindrome(words): words.sort() # Step 1 longest_palindrome = "" # Step 2

for i in range(len(words)-1): # Step 3
    for j in range(i+1, len(words)):
        candidate = words[i] + words[j]
        if candidate == candidate[::-1]: # Step 4
            if len(candidate) > len(longest_palindrome):
                longest_palindrome = candidate
                
return longest_palindrome # Step 5

Time Complexity:

We are iterating through each pair of words in the input list, so the time complexity of this solution is O(n^2) where n is the number of words in the input list.

Space Complexity:

We are using constant extra space to store the longest_palindrome variable, so the space complexity of this solution is O(1).

Longest Palindrome By Concatenating Two Letter Words Solution Code

1