Leetcode 868 Solution

This article provides solution to leetcode question 868 (push-dominoes)

https://leetcode.com/problems/push-dominoes

Solution

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        m = collections.defaultdict(int)
        ans = ['.'] * len(dominoes)

        for i, domino in enumerate(dominoes):
            if domino == 'L':
                m[i] = -1
                ans[i] = 'L'
            elif domino == 'R':
                m[i] = 1
                ans[i] = 'R'

        while m:
            next_m = collections.defaultdict(int)

            for i, direction in m.items():
                if direction == -1 and i > 0 and ans[i - 1] == '.':
                    next_m[i - 1] += direction
                elif direction == 1 and i < len(ans) - 1 and ans[i + 1] == '.':
                    next_m[i + 1] += direction

            m = collections.defaultdict(int)
            for i, direction in next_m.items():
                if direction:
                    m[i] = direction
                    ans[i] = 'L' if direction == -1 else 'R'

        return ''.join(ans)