In this video, I explain the algorithm behind solving Leetcode problem 2131 Longest Palindrome by Concatenating Two Letter Words.
Since we are searching for keys (and their count) and their matches (with their count as well) I opt for a solution using hashmaps. Hashmaps allow us to search for keys in constant time O(1). I start by counting the words that I have and grouping them into two maps. The first map contains normal two-letter words while the second contains words that are already palindromes (double letters).
I then proceed with the first map where I go through each key and find its matching string. I count accordingly how many palindromes can be formed from the matching keys. I move then to the second map which already contains palindromes. I take an even number of occurrences for every key, and if I'm left with any double-letter palindrome, I consider only one of them at the end.
This results in a solution that uses O(n) time and space.
I explained things relatively slowly in this video and it can be safely watched at 2x.
00:00 Introduction + understanding the problem
04:32 Counting strings and grouping them in two hashmaps
07:43 Counting the length of the palindrome that can be formed from strings with different letters
14:04 Counting the length of the palindrome that can be formed from strings with double letters
18:50 Reversing two-letter strings
19:59 Fixing typos
20:33 Result and complexity analysis