Reverse Shuffle Merge

  • + 0 comments

    Rather simplistic greedy approach (Python3) in 30 lines total:

    from collections import Counter
    
    def reverseShuffleMerge(s):
        # find character frequencies in the desired string A
        freq = {key: val // 2 for key, val in Counter(s).items()}
    
        # repeat gready approach until solution is complete
        solution = []
        n = len(s)
        while len(solution) < n // 2:
            left_freq = Counter(s)
            next_char = {}
            min_char = '~'
            # search original string S backwards
            for index in range(len(s)-1, -1, -1):
                char = s[index]
                # it is possible to take this char as the next one
                if char not in next_char and freq[char] > 0:
                    next_char[char] = index
                    min_char = min(min_char, char)
                # there's not enough letters available to the left
                left_freq[char] -= 1
                if left_freq[char] < freq[char]:
                    break
            # add minimal char as the next one (greedy)
            solution += min_char
            freq[min_char] -= 1
            s = s[0:next_char[min_char]]
    
        return "".join(solution)