Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Last active May 2, 2025 18:05
Show Gist options
  • Save Ifihan/4d4c199638a83c4422a337a47ab0c998 to your computer and use it in GitHub Desktop.
Save Ifihan/4d4c199638a83c4422a337a47ab0c998 to your computer and use it in GitHub Desktop.
Push Dominoes

Question

Approach

When solving this, I imagined the dominoes as experiencing "forces" from left and right. Each domino receives a force from the closest 'R' to its left or 'L' to its right. The closer the source, the stronger the force. I assigned a large positive value when a domino was pushed to the right ('R') and a large negative value when pushed to the left ('L'). Then I scanned the string twice:

  • Left to Right: I assigned decreasing positive forces after each 'R' and reset after 'L'.
  • Right to Left: I assigned decreasing negative forces after each 'L' and reset after 'R'.

Finally, I added the forces at each position:

  • Positive: falls right 'R'
  • Negative: falls left 'L'
  • Zero: stays '.'

Implementation

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        n = len(dominoes)
        forces = [0] * n

        force = 0
        for i in range(n):
            if dominoes[i] == 'R':
                force = n
            elif dominoes[i] == 'L':
                force = 0
            else:
                force = max(force - 1, 0)
            forces[i] += force

        force = 0
        for i in range(n - 1, -1, -1):
            if dominoes[i] == 'L':
                force = n
            elif dominoes[i] == 'R':
                force = 0
            else:
                force = max(force - 1, 0)
            forces[i] -= force

        # Build final result
        result = []
        for f in forces:
            if f > 0:
                result.append('R')
            elif f < 0:
                result.append('L')
            else:
                result.append('.')

        return ''.join(result)

Complexities

  • Time: O(n)
  • Space: O(n)
image
  • Space: O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment