FastPrepMerging Palindromes

Merging Palindromes

Old Mission logoOld Mission● MediumFULLTIMEOA
Learn

Problem statement

From the letters of first, choose a multiset that can be rearranged into a palindrome. Do the same independently for second. Combine the two chosen multisets and rearrange them into one palindrome.

Return the longest palindrome obtainable this way. If several have maximum length, return the lexicographically smallest.

Function

mergingPalindromes(first: String, second: String) → String

Examples

Example 1

first = "aabbc"second = "ddefefq"return = "abdefcfedba"

Use every available pair from both strings. Among the remaining odd-count letters, c is the smallest possible center, producing the lexicographically smallest maximum-length palindrome.

Example 2

first = "abc"second = "xyz"return = "a"

No character forms a pair in either string. A one-character palindrome is optimal, and a is lexicographically smallest.

Constraints

  • 1 <= first.length, second.length <= 200000
  • Both strings contain lowercase English letters only.

More Old Mission problems

See Old Mission hiring insights
public String mergingPalindromes(String first, String second) {
  // Write your code here.
}
first"aabbc"
second"ddefefq"
expected"abdefcfedba"
Checking account…