Leetcode Problem 2131. Longest Palindrome by Concatenating Two Letter Words

2131. Longest Palindrome by Concatenating Two Letter Words

Leetcode Solutions

Hash Map Approach for Longest Palindrome Creation

  1. Initialize a hash map to count the occurrences of each word.
  2. Iterate over the input array, incrementing the count for each word in the hash map.
  3. Initialize answer to 0 and central to false.
  4. For each word in the hash map that is a palindrome (the word is the same as its reverse), add the count to answer if it's even, or add count - 1 and set central to true if it's odd.
  5. For each non-palindromic word, add 2 * min(count[word], count[reverseWord]) to answer.
  6. If central is true, add 1 to answer.
  7. Return 2 * answer as the final length of the palindrome.
UML Thumbnail

Two-Dimensional Array Approach for Longest Palindrome Creation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...