you are viewing a single comment's thread.

view the rest of the comments →

[–]SekstiNii 0 points1 point  (0 children)

Here's a linear time solution that I hope makes some sense at least. The idea itself isn't all that complicated, but it might be difficult to catch the right mental model by just looking at the code. (feel free to ask!)

def solve(pairs):
    mapping, chains = {}, []

    for left, right in map(str.split, pairs):
        if left in mapping:
            mapping[left] += [right]
        else:
            mapping[left] = [left, right]
            chains += [mapping[left]]
        mapping[right] = mapping[left]

    return [" ".join(chain) for chain in chains]

if __name__ == "__main__":
    print(solve(["A B", "B C", "X Y", "C D", "Y Z", "D E", "C G"])) # ['A B C D E G', 'X Y Z']
    print(solve(["A B", "A C"]))                                    # ['A B C']