⚡Flashcard Drill➔
NeetCode #125LC-838MediumArrays & Hashing
← Back to All Problems

#125 · #838 · Push Dominoes(推多米诺)

📌 Problem Statement & Constraints

Given a string dominoes where dominoes[i] is 'L', 'R' or '.', return the final state after all falling dominoes settle. A domino pushed left forces its left neighbour to fall left, and so on; when an 'R' and an 'L' meet, the ones between them stay upright. Constraints: 1 <= dominoes.length <= 10^4.

💡 Core Algorithmic Approaches

  1. Model the forces numerically: R contributes a positive force decaying by 1 per step to the right, L a negative force decaying to the left.
  2. Sweep left to right accumulating the rightward force: reset to a large value on R, reset to 0 on L, and decrement by 1 on ..
  3. Sweep right to left accumulating the leftward force symmetrically, and add it to the same array.
  4. The final state is R where the total force is positive, L where negative, and . where it is zero -- which is exactly where the two forces cancel.

💻 Benchmark Python3 Implementation

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        n = len(dominoes)
        force = [0] * n
        # rightward force from 'R'
        f = 0
        for i in range(n):
            if dominoes[i] == "R":
                f = n                      # strong enough to reach any distance
            elif dominoes[i] == "L":
                f = 0
            else:
                f = max(f - 1, 0)          # decay, but never negative
            force[i] += f
        # leftward force from 'L'
        f = 0
        for i in range(n - 1, -1, -1):
            if dominoes[i] == "L":
                f = n
            elif dominoes[i] == "R":
                f = 0
            else:
                f = max(f - 1, 0)
            force[i] -= f                  # leftward force is negative
        return "".join("R" if v > 0 else ("L" if v < 0 else ".") for v in force)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): two linear sweeps.
💾 Space Complexity
O(n) for the force array.

⚠️ Interview Pitfalls & Follow-ups

  • Using a stack or simulating rounds: correct but O(n^2) in the worst case; the two-pass force accumulation is O(n).
  • Forgetting the decay (f - 1): the force would act across the whole string instead of stopping after a few cells.
  • Using f -= 1 without the max(..., 0): the force would become negative and leak past the boundary.
  • Treating an R and an L meeting with an odd gap: the middle cell stays upright when the gap is odd, which the equal-force cancellation handles automatically.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

推多米诺

n 张多米诺骨牌排成一行,将每张骨牌垂直竖立。在开始时,同时把一些骨牌向左或向右推。给定一个字符串 dominoes,表示这一行的初始状态: dominoes[i] = "L" 表示第 i 张骨牌被向左推; "R" 表示被向右推; "." 表示没有被推动。每过一秒,被推动的骨牌会推动相邻的骨牌。如果一张竖直的骨牌同时受到左右两侧的力,它会保持竖直(因为力相互抵消)。返回表示最终状态的字符串。约束:n == dominoes.length;1 ≤ n ≤ 10^5;dominoes[i] 为 "L"、"R" 或 "."。

核心要点

  • 两遍扫描计算合力(标准解) :为每个位置维护一个「力」值。
  • 左→右扫描统计向右的力 :遇到 R 则力重置为 n(足够大);遇到 L 则力归零;遇到 . 则力减一(但不小于 0)。把当前力累加到该位置。
  • 右→左扫描统计向左的力 :对称地,遇到 L 则力重置为 n;遇到 R 则归零; . 则减一。把当前力从该位置 减去 。
  • 根据合力符号判定 :合力为正说明向右的力更强,输出 R ;为负说明向左的力更强,输出 L ;为零说明抵消,输出 . 。
  • 为什么用「力」而非模拟 :逐秒模拟需要 O(n · 时间) 的时间,而力的衰减模型把问题转化为两次线性扫描,O(n)。

常见陷阱

  • 用逐秒模拟 :需要 O(n · 时间) 的复杂度,最坏情况(如 "R....L" 中距离很远)会退化。力模型是 O(n)。
  • 力的初值取太小 :若用 1 作为初值,远距离传播会衰减到 0,无法正确表示「力的大小」。必须取 ≥ n 的值(如 n),保证在 n 步内不会衰减到 0。
  • max(f - 1, 0) 忘记下限 :力不能为负,否则会被错误地累加为负值,导致后续位置判定错误。
  • 两个方向的力没有正确相减 :左扫描是 += ,右扫描是 -= ,最终合力符号决定方向。写成同号相加会完全失效。
  • 忘记 dominoes[i] == "R" 时把 f 归零(右扫描中) : R 会阻挡来自右侧的 L 的力,必须归零。

参考实现

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

        # 左 -> 右:统计向右的力
        f = 0
        for i in range(n):
            if dominoes[i] == 'R':
                f = n                       # 足够大的初值
            elif dominoes[i] == 'L':
                f = 0
            else:
                f = max(f - 1, 0)
            force[i] += f

        # 右 -> 左:统计向左的力
        f = 0
        for i in range(n - 1, -1, -1):
            if dominoes[i] == 'L':
                f = n
            elif dominoes[i] == 'R':
                f = 0
            else:
                f = max(f - 1, 0)
            force[i] -= f

        return ''.join('R' if v > 0 else ('L' if v < 0 else '.') for v in force)