Longest Palindrome by Concatenating Two-Letter Words
Explore how to construct the longest palindrome by concatenating given two-letter words. Learn to efficiently track word usage and handle constraints to solve this pattern-based problem commonly seen in coding interviews.
We'll cover the following...
Statement
Suppose you are given an array of strings, words, and each element in the array has a length of two. You need to return the length of the longest palindrome that can be made by concatenating some elements from words.
If no palindrome can be made, return 0.
A palindrome is a sequence of characters that reads the same forward and backward.
Constraints:
-
words.length words[i].length- Each word can be used at most once.
wordsshould only consist of lowercase English letters.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Longest Palindrome by Concatenating Two-Letter Words
What is the length of the longest palindrome that can be constructed from the words in the input array below?
words = [“ab”, “cd”, “ef”, “gh”, “ij”]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
def longest_palindrome(words):# Replace this placeholder return statement with your codereturn -1