Ctrl K

Palindrome From Two-Letter Cards

Medium
Each card in the array cards carries two lowercase English letters. Choose some of the cards (each at most once) and lay them out in a row in any order so that the resulting string is a palindrome, reading the same left to right and right to left. Return the greatest possible length of such a string. If no palindrome can be built, return 0.
Example 1
cards=["ok", "mm", "ko", "ok"] → 6

"ok" + "mm" + "ko" = "okmmko", length 6. The second "ok" card has no partner.

Example 2
cards=["zz", "zz", "zz", "ab"] → 6

All three "zz" cards together give "zzzzzz", length 6. The "ab" card cannot be used.

Example 3
cards=["pq", "rs"] → 0

No card is a palindrome by itself and none has a mirror partner, so the answer is 0.

Constraints
  • 1 ≤ len(cards) ≤ 10⁵
  • len(cards[i]) = 2
  • cards[i] consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPalindromes From Shared Letters MediumJobs With a Cooldown MediumMost Searched Words MediumNo Twin Letters Side by Side MediumDomain Visit Rollup Medium
loading Python…
Input
cards=["ok", "mm", "ko", "ok"]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 55 tests on the server, hidden ones included.