Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an array of strings words. Each element of words consists of two lowercase English letters.
Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.
Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.
A palindrome is a string that reads the same forward and backward.
Example 1:
Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created.
Example 2:
Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created.
Example 3:
Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx".
Constraints:
1 <= words.length <= 105words[i].length == 2words[i] consists of lowercase English letters.Problem summary: You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
["lc","cl","gg"]
["ab","ty","yt","lc","cl","ab"]
["cc","ll","xx"]
palindrome-pairs)longest-palindrome)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2131: Longest Palindrome by Concatenating Two Letter Words
class Solution {
public int longestPalindrome(String[] words) {
Map<String, Integer> cnt = new HashMap<>();
for (var w : words) {
cnt.merge(w, 1, Integer::sum);
}
int ans = 0, x = 0;
for (var e : cnt.entrySet()) {
var k = e.getKey();
var rk = new StringBuilder(k).reverse().toString();
int v = e.getValue();
if (k.charAt(0) == k.charAt(1)) {
x += v & 1;
ans += v / 2 * 2 * 2;
} else {
ans += Math.min(v, cnt.getOrDefault(rk, 0)) * 2;
}
}
ans += x > 0 ? 2 : 0;
return ans;
}
}
// Accepted solution for LeetCode #2131: Longest Palindrome by Concatenating Two Letter Words
func longestPalindrome(words []string) int {
cnt := map[string]int{}
for _, w := range words {
cnt[w]++
}
ans, x := 0, 0
for k, v := range cnt {
if k[0] == k[1] {
x += v & 1
ans += v / 2 * 2 * 2
} else {
rk := string([]byte{k[1], k[0]})
if y, ok := cnt[rk]; ok {
ans += min(v, y) * 2
}
}
}
if x > 0 {
ans += 2
}
return ans
}
# Accepted solution for LeetCode #2131: Longest Palindrome by Concatenating Two Letter Words
class Solution:
def longestPalindrome(self, words: List[str]) -> int:
cnt = Counter(words)
ans = x = 0
for k, v in cnt.items():
if k[0] == k[1]:
x += v & 1
ans += v // 2 * 2 * 2
else:
ans += min(v, cnt[k[::-1]]) * 2
ans += 2 if x else 0
return ans
// Accepted solution for LeetCode #2131: Longest Palindrome by Concatenating Two Letter Words
/**
* [2131] Longest Palindrome by Concatenating Two Letter Words
*
* You are given an array of strings words. Each element of words consists of two lowercase English letters.
* Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.
* Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.
* A palindrome is a string that reads the same forward and backward.
*
* Example 1:
*
* Input: words = ["lc","cl","gg"]
* Output: 6
* Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
* Note that "clgglc" is another longest palindrome that can be created.
*
* Example 2:
*
* Input: words = ["ab","ty","yt","lc","cl","ab"]
* Output: 8
* Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
* Note that "lcyttycl" is another longest palindrome that can be created.
*
* Example 3:
*
* Input: words = ["cc","ll","xx"]
* Output: 2
* Explanation: One longest palindrome is "cc", of length 2.
* Note that "ll" is another longest palindrome that can be created, and so is "xx".
*
*
* Constraints:
*
* 1 <= words.length <= 10^5
* words[i].length == 2
* words[i] consists of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
// discuss: https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn longest_palindrome(words: Vec<String>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2131_example_1() {
let words = vec_string!["lc", "cl", "gg"];
let result = 6;
assert_eq!(Solution::longest_palindrome(words), result);
}
#[test]
#[ignore]
fn test_2131_example_2() {
let words = vec_string!["ab", "ty", "yt", "lc", "cl", "ab"];
let result = 8;
assert_eq!(Solution::longest_palindrome(words), result);
}
#[test]
#[ignore]
fn test_2131_example_3() {
let words = vec_string!["cc", "ll", "xx"];
let result = 2;
assert_eq!(Solution::longest_palindrome(words), result);
}
}
// Accepted solution for LeetCode #2131: Longest Palindrome by Concatenating Two Letter Words
function longestPalindrome(words: string[]): number {
const cnt = new Map<string, number>();
for (const w of words) cnt.set(w, (cnt.get(w) || 0) + 1);
let [ans, x] = [0, 0];
for (const [k, v] of cnt.entries()) {
if (k[0] === k[1]) {
x += v & 1;
ans += Math.floor(v / 2) * 2 * 2;
} else {
ans += Math.min(v, cnt.get(k[1] + k[0]) || 0) * 2;
}
}
ans += x ? 2 : 0;
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.