We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defreverseShuffleMerge(s):fromcollectionsimportCounter# Calculate the frequency of each character in sfreq=Counter(s)# Calculate the required frequency for Arequired={char:freq[char]// 2 for char in freq}# Initialize counts of used charactersused={char:0forcharinfreq}result=[]# Iterate over the string in reverse orderforcharinreversed(s):ifused[char]<required[char]:# Ensure that we are making the lexicographically smallest resultwhileresultandresult[-1]>charandused[result[-1]]+freq[result[-1]]>required[result[-1]]:removed_char=result.pop()used[removed_char]-=1result.append(char)used[char]+=1# Decrease the frequency count as we have processed this characterfreq[char]-=1# Convert result list to a string and returnreturn''.join(result)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Reverse Shuffle Merge
You are viewing a single comment's thread. Return to all comments →