Push Dominoes (LeetCode 838): Solution and Explanation
A line of dominoes starts with some pushed left (L), some pushed right (R) and the rest upright (.). Falling dominoes push their neighbours each second, and a domino pushed from both sides at once stays up. Return the final line.
Intuition
Simulating second by second works but can take O(n) rounds of O(n) work. The better question is: for an upright domino, what decides its fate? Only the nearest pushed domino to its left and the nearest pushed domino to its right. Anything further away is blocked by those two.
So split the line at every pushed domino. Each run of dots is bounded by two letters, and there are only four cases. R...R and L...L: the push travels through the whole run, so everything falls the same way. L...R: both ends lean away, so nothing in between moves.
The interesting case is R...L. Both pushes travel inward at one domino per second. A domino falls toward whichever end is closer, so the left half falls right and the right half falls left. When the run has odd length, the middle domino is reached by both pushes in the same second and stays upright.
The ends of the string need care: dots before the first letter or after the last one have only one neighbour. Padding the string with an L on the left and an R on the right fixes this. Those walls lean away from the line, so they never push anything, but now every run has a letter on both sides.
Approach: Two pointers over pushed dominoes
- Build
s = 'L' + dominoes + 'R'and copy it intores. - Keep
lefton the last pushed domino seen. Moverightforward and skip dots. - When
s[right]is a letter: ifs[left] == s[right], set every domino between them to that letter. - If
s[left] == 'R'ands[right] == 'L', walkloup fromleft + 1andhidown fromright - 1, writing R and L, until they meet. An odd middle stays.. - If it is
L ... R, leave the gap alone. Then setleft = right. - Return
reswithout the two padding characters.
Step-by-step example
dominoes = ".L.R...LR..L.."
- Pad to
L.L.R...LR..L..R(indices shift by one). - Wall L and the L at padded index 2 are both L, so the dot between them falls left: the line starts with
LL. - L at 2 and R at 4: they lean apart, so the dot at 3 stays up.
- R at 4 and L at 8: three dots. One falls right, one falls left, and the middle one stays: so
R...LbecomesRR.LL. - L at 8 and R at 9 are neighbours, nothing to do. R at 9 and L at 12: two dots, one falls each way.
- L at 12 and the wall R at 15: they lean apart, so the last two dots stay. The answer is
LL.RR.LLRRLL...
Code: Python, Java, C++
1class Solution:
2 def pushDominoes(self, dominoes: str) -> str:
3 s = 'L' + dominoes + 'R'
4 res = list(s)
5 left = 0
6 for right in range(1, len(s)):
7 if s[right] == '.':
8 continue
9 if s[left] == s[right]:
10 for k in range(left + 1, right):
11 res[k] = s[left]
12 elif s[left] == 'R' and s[right] == 'L':
13 lo, hi = left + 1, right - 1
14 while lo < hi:
15 res[lo] = 'R'
16 res[hi] = 'L'
17 lo += 1
18 hi -= 1
19 left = right
20 return ''.join(res[1:-1])1class Solution {
2 public String pushDominoes(String dominoes) {
3 String s = "L" + dominoes + "R";
4 char[] res = s.toCharArray();
5 int left = 0;
6 for (int right = 1; right < s.length(); right++) {
7 if (s.charAt(right) == '.') continue;
8 if (s.charAt(left) == s.charAt(right)) {
9 for (int k = left + 1; k < right; k++) res[k] = s.charAt(left);
10 } else if (s.charAt(left) == 'R' && s.charAt(right) == 'L') {
11 int lo = left + 1, hi = right - 1;
12 while (lo < hi) {
13 res[lo++] = 'R';
14 res[hi--] = 'L';
15 }
16 }
17 left = right;
18 }
19 return new String(res, 1, res.length - 2);
20 }
21}1class Solution {
2public:
3 string pushDominoes(string dominoes) {
4 string s = "L" + dominoes + "R";
5 string res = s;
6 int left = 0;
7 for (int right = 1; right < (int)s.size(); right++) {
8 if (s[right] == '.') continue;
9 if (s[left] == s[right]) {
10 for (int k = left + 1; k < right; k++) res[k] = s[left];
11 } else if (s[left] == 'R' && s[right] == 'L') {
12 int lo = left + 1, hi = right - 1;
13 while (lo < hi) {
14 res[lo++] = 'R';
15 res[hi--] = 'L';
16 }
17 }
18 left = right;
19 }
20 return res.substr(1, res.size() - 2);
21 }
22};Time and space complexity
O(n)
The right pointer visits each index once, and every domino between two letters is written at most once.
O(n)
The padded copy and the result array each hold n + 2 characters.
Other approaches
Net force from both directions (time O(n), space O(n))
Sweep left to right giving each domino a right force that decays with distance from the last R, then sweep right to left for the L force. A domino falls toward the larger force and stays up on a tie. Same complexity, but uses two integer arrays.
Second-by-second simulation (time O(n^2), space O(n))
Repeatedly apply one second of pushes until nothing changes. It matches the statement directly, which makes it a good brute-force checker, but long chains need O(n) rounds.
Common mistakes
- Forgetting the dots before the first letter or after the last one. Padding with
LandRwalls handles both ends with no special cases. - Letting the middle domino of an odd
R...Lgap fall. It is hit from both sides in the same second and stays upright. - Filling an
L...Rgap. Those ends lean away from each other, so the gap does not change. - Updating the string you are scanning. Read letters from the original
sand write into a separateres, so a freshly filled gap does not look like a new push.
Frequently asked questions
Why can a domino ignore pushes from farther away?
A push travels through dominoes one at a time. Any push from further left must pass the nearest pushed domino on that side first, and that domino is already falling, so the far push adds nothing.
Why do the padding walls not change the answer?
The left wall falls left, away from the line, and the right wall falls right, also away. They never push a real domino, they only make every gap look like it has two ends.
Is this really dynamic programming?
It is often listed under DP because the force-based version builds each domino's force from its neighbour's. The two-pointer version shown here is the same idea with the forces collapsed into the four gap rules.