Atlassian | OA | Merging Palindromes
Anonymous User
1891

Question Level: Medium - Hard
Merging Palindromes
Given two strings, find all palindromes that can be formed with the letters of each string. From those palindromes, select one from each set that, when combined and rearranged, produces the longest palindrome posslble. If there are multiple palindromes of that length, choose the alphabeticaly smallest of them.
Example
s1 = 'aabbc'
s2 = 'ddefefq'
Rest information given in the images below

Solved by @anarchaworld, Same concept implemented in python by @callistopan. Thank you very much both of you

def merging(a ,b):
    count_a =[0]*26
    count_b=[0]*26
    
    for ch in a:
        count_a[ord(ch)-ord('a')]+=1

    for ch in b:
        count_b[ord(ch)-ord('a')]+=1

    mid=''
    res=''
    for i in range(26):

        curr = chr(i+ord('a'))

        if count_a[i]%2==1 and count_b[i]%2==1 and len(mid)<2:
            mid=curr*2

        if (count_a[i]%2==1 or count_b[i]%2==1) and mid=='':
            mid=curr

        res+=(curr*(count_a[i]//2+count_b[i]//2))
        

    # sort the res
    if len(mid)==2:
        res=''.join(sorted(res+mid[0] ))
        return res+res[::-1]

    return res+mid+res[::-1]

I got this question in the Atlassian Coding Test but was unable to solve them.

image
image

Comments (5)