↓Skip to main content
  1. LeetCode/

LeetCode 2131: Longest Palindrome by Concatenating Two Letter Words

·2 mins· ·
LeetCode Medium Greedy Hash-Table String Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-08-21

  • Submissions: Wrong Answer → Accepted

Approach
#

A palindrome is symmetric, so each word needs its reverse on the other side:

  • "ab" pairs with "ba", one on each side, +4.
  • A self-palindrome like "cc" can pair with another "cc"; one leftover can go in the middle for +2, and only one word in total can.

My Attempts
#

Attempt 1 treated every self-palindrome as a middle candidate and skipped it. For ["cc", "cc"] the answer is 4 ("cccc"); it returned 2.

Pairing every word with its reverse first (the reverse of "cc" is itself) and adding 2 if any palindrome is left over passed.

Solution
#

class Solution:
    def longestPalindrome(self, words: List[str]) -> int:
        cnt = Counter(words)
        res, mid = 0, False
        for w, c in cnt.items():
            r = w[::-1]
            if w == r:
                res += c // 2 * 4          # pair up on both sides
                mid |= c % 2 == 1          # one leftover can go in the middle
            elif w < r:                    # count each pair once
                res += min(c, cnt[r]) * 4
        return res + (2 if mid else 0)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Self-palindromes can pair with each other; they are not all middle-only.
  • At most one word goes in the middle.
  • w < r keeps "ab" and "ba" from being counted twice.

Interview Explanation
#

I count each word. A non-palindrome pairs with its reverse, using the smaller count; a self-palindrome pairs with itself, and an odd count leaves one for the middle. Each pair adds 4 and the middle adds 2. Time O(n).

Related

LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 min
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 note: reducing the number of kinds means deleting whole kinds, starting from the least frequent
LeetCode 1410: HTML Entity Parser
·2 mins
LeetCode Medium Hash-Table String
LeetCode 1410 note: scan left to right, trying all six entities at each position and skipping past a match; chained replace does not work
LeetCode 3518: Smallest Palindromic Rearrangement II
·3 mins
LeetCode Hard Math Combinatorics Counting Hash-Table String
LeetCode 3518 note: a palindrome is determined by its left half, so this is the k-th permutation of a multiset; try characters position by position and use permutation counts, updated in O(1), to find k’s branch
LeetCode 3121: Count the Number of Special Characters II
·2 mins
LeetCode Medium Hash-Table String
LeetCode 3121 note: track each letter’s last lowercase index and first uppercase index; it counts only when the former comes first
LeetCode 1814: Count Nice Pairs in an Array
·1 min
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 note: rearrange the condition into nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]), count pairs per value, and remember the modulus
LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·2 mins
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 note: count each value on and off the Y, enumerate the Y value a and background value b (a != b), and take the fewest cells to change