Reverse Shuffle Merge

  • + 0 comments
    def reverseShuffleMerge(s):
        from collections import Counter
    
        # Calculate the frequency of each character in s
        freq = Counter(s)
        
        # Calculate the required frequency for A
        required = {char: freq[char] // 2 for char in freq}
        
        # Initialize counts of used characters
        used = {char: 0 for char in freq}
        
        result = []
        # Iterate over the string in reverse order
        for char in reversed(s):
            if used[char] < required[char]:
                # Ensure that we are making the lexicographically smallest result
                while result and result[-1] > char and used[result[-1]] + freq[result[-1]] > required[result[-1]]:
                    removed_char = result.pop()
                    used[removed_char] -= 1
    
                result.append(char)
                used[char] += 1
            
            # Decrease the frequency count as we have processed this character
            freq[char] -= 1
        
        # Convert result list to a string and return
        return ''.join(result)