Push Dominoes — LeetCode 838 Python Solution

MediumTwo PointersStringDynamic Programming
Problem
#838
Reading time
5 min

The problem

There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

Example

Input
dominoes = "RR.L"
Output
"RR.L"
Explanation
The first domino expends no additional force on the second domino.

Python solution

Python
class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        n = len(dominoes)
        q = deque()
        time = [-1] * n
        force = defaultdict(list)
        for i, f in enumerate(dominoes):
            if f != '.':
                q.append(i)
                time[i] = 0
                force[i].append(f)
        ans = ['.'] * n
        while q:
            i = q.popleft()
            if len(force[i]) == 1:
                ans[i] = f = force[i][0]
                j = i - 1 if f == 'L' else i + 1
                if 0 <= j < n:
                    t = time[i]
                    if time[j] == -1:
                        q.append(j)
                        time[j] = t + 1
                        force[j].append(f)
                    elif time[j] == t + 1:
                        force[j].append(f)
        return ''.join(ans)

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(n), where n is the number of dominoes auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 838. Push Dominoes is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 838. Push Dominoes?
LeetCode 838. Push Dominoes is rated Medium on LeetCode.
What is the time complexity of LeetCode 838. Push Dominoes?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 838. Push Dominoes?
The Python solution on this page uses O(n), where n is the number of dominoes auxiliary space.
What topics does LeetCode 838. Push Dominoes cover?
LeetCode 838. Push Dominoes is tagged Two Pointers, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview