Push Dominoes

Work out how a row of dominoes settles after some of them are pushed left or right.

A row of dominoes is given as a string dominoes. Each character is one domino: 'L' means it was pushed to the left, 'R' means it was pushed to the right, and '.' means it is standing upright. All the pushes happen at the same moment. Every second, a domino falling left knocks over the upright domino on its left, and a domino falling right knocks over the upright domino on its right. An upright domino hit from both sides in the same second stays upright. A falling domino does not push a domino that is already falling. Return the row once nothing moves any more.

Example 1
Input: dominoes = "RR.L"
Output: "RR.L"
Explanation: the third domino is hit from both sides in the same second, so it stays upright.
Example 2
Input: dominoes = ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Solution

The Idea

You have probably set up a row of dominoes and tipped one over. Here several are tipped at once, some to the left and some to the right, and the question is what the row looks like when everything has stopped.

Take Example 2, ".L.R...LR..L..", and follow it second by second, counting positions from 0. The L at position 1 knocks over the domino on its left. The R at position 3 knocks over position 4, and the L at position 7 knocks over position 6. In the next second, position 5 is hit from both sides and stays up. That works, but it means replaying the row second after second. Is there a way to see the answer without the replay?

Notice that an upright domino can only be reached by the nearest pushed domino on each side. Anything further away has to travel through that pushed domino, and a falling domino does not push one that is already falling. So the pushed dominoes cut the row into gaps, and each run of upright dominoes is decided by its two ends alone. Look at the picture below.

Example 2 with an imaginary L before the row and an imaginary R after it. The brackets mark the gaps between pushed dominoes: L L all fall left, L R stay upright, R L meet in the middle, R L meet in the middle, L R stay upright. The R...L gap becomes RR.LL in the bottom row.

The top row is Example 2, and the bottom row is the result. Under each gap, the bracket shows the letters at its two ends. There are only four kinds of gap:

  • L, then L: the right end falls left and knocks over every domino in the gap, so they all fall left.
  • R, then R: the same, the other way round. They all fall right.
  • L, then R: both ends fall away from the gap, so the dominoes in it stay upright.
  • R, then L: both ends fall into the gap, and the two falls meet in the middle. The left half falls right and the right half falls left.

Look at the highlighted gap, R...L. Its three upright dominoes become RR.LL: one falls right, one falls left, and the middle one is hit from both sides at once, so it stays up. The next gap, R..L, has two upright dominoes and becomes RRLL, with nothing left in the middle. Between the L at position 7 and the R at position 8 there is no upright domino at all, so that gap has no bracket.

What about the upright dominoes, the dots, before the first pushed domino and after the last one? They have a pushed domino on one side only. The dashed boxes in the picture solve that: an imaginary L before the row and an imaginary R after it. Both fall away from the row, so they never push anything. With them, every run of dots sits between two ends, and the four kinds of gap cover the whole row.

Solution Approach

Turning that idea into code means settling three things: how to find the gaps, how to fill each kind of gap, and what to do at the two ends of the row.

Finding the gaps

How do we find each gap and its two ends in one walk along the row? Keep the position of the last pushed domino seen, prev. Walk along the row and skip dots. At each 'L' or 'R', the dominoes between prev and here form one gap, with prev as its left end and the current domino as its right end. Fill the gap, then move prev here.

The simple way, replaying the row one second at a time, may need as many seconds as there are dominoes. With n dominoes and a single 'R' at the start, it takes about n seconds, and each second scans the whole row, so the replay costs about n² steps. The walk over the gaps touches each domino a fixed number of times.

Filling each kind of gap

What does each kind of gap write? When both ends have the same letter, every position in the gap gets that letter. When the left end is 'R' and the right end is 'L', two markers fill the gap from both sides: lo starts just after the left end and writes 'R', hi starts just before the right end and writes 'L', and they step toward each other.

They stop as soon as lo is no longer left of hi. With an odd number of dots, the two markers land on the middle domino at the same time and leave it as '.'. With an even number, they cross and the gap is full. When the left end is 'L' and the right end is 'R', there is nothing to write.

The ends of the row

How do the imaginary dominoes get into the row? Build a new string, "L" + dominoes + "R", and run the walk on it. At the end, copy out everything except the first and last character, which removes the two imaginary dominoes again.

Java Solution

The method pushDominoes works in these steps:

  1. First, add the imaginary ends: s is "L" + dominoes + "R". Copy it into a char array, result, which the gaps are written into.
  2. Set prev to 0, the imaginary 'L'. Then a loop moves i along s from position 1 and skips every '.'.
  3. At a pushed domino, read the two ends of the gap: left is the letter at prev, and right is the letter at i.
  4. If left and right are the same, a short loop with k writes that letter into every position between them.
  5. If left is 'R' and right is 'L', a loop with two markers, lo and hi, writes 'R' from the left and 'L' from the right while lo < hi. For 'L' then 'R', nothing is written.
  6. Move prev to i, and carry on with the next character.
  7. When the loop is done, return the characters of result from position 1, dominoes.length() of them, which leaves out the two imaginary ends.

The main method runs both examples, then gaps of three and of two dots between R and L. It ends with one push to the right, one push to the left, and a row where nothing is pushed.

Java
public class PushDominoes {

    public static String pushDominoes(String dominoes) {
        String s = "L" + dominoes + "R";      // imaginary ends that push nothing inward
        char[] result = s.toCharArray();
        int prev = 0;                         // position of the last pushed domino seen
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == '.') {
                continue;
            }
            char left = s.charAt(prev);
            char right = s.charAt(i);
            if (left == right) {              // L...L or R...R: all fall the same way
                for (int k = prev + 1; k < i; k++) {
                    result[k] = left;
                }
            } else if (left == 'R') {         // R...L: each half falls toward the middle
                for (int lo = prev + 1, hi = i - 1; lo < hi; lo++, hi--) {
                    result[lo] = 'R';
                    result[hi] = 'L';
                }
            }                                 // L...R: the dominoes between stay upright
            prev = i;
        }
        return new String(result, 1, dominoes.length());
    }

    public static void main(String[] args) {
        String[] tests = {"RR.L", ".L.R...LR..L..", "R...L", "R..L", "..R..", "..L..", "..."};
        for (String d : tests) {
            System.out.println("\"" + d + "\" -> \"" + pushDominoes(d) + "\"");
        }
    }
}

Running it prints:

Output
"RR.L" -> "RR.L"
".L.R...LR..L.." -> "LL.RR.LLRRLL.."
"R...L" -> "RR.LL"
"R..L" -> "RRLL"
"..R.." -> "..RRR"
"..L.." -> "LLL.."
"..." -> "..."

Look at "R...L" -> "RR.LL" and the line after it, "R..L" -> "RRLL". With three dots, lo and hi both reach the middle position, the loop stops, and the middle domino stays '.'. With two dots, they cross and every position is filled. That stop condition matters: with lo <= hi the loop also runs on the middle domino, writes 'R' and then 'L' there, and "R...L" prints "RRLLL". Example 1 then prints "RRLL" instead of "RR.L".

In "..R.." -> "..RRR", the dots before the R sit between the imaginary L and that R, so they stay up, and the dots after it fall right, toward the imaginary R. "..L.." -> "LLL.." is the mirror image. The last line, "...", is a single gap from the imaginary L to the imaginary R, so nothing falls.

The original implementation, PushDominoes.java, is on GitHub.

Complexity

The work is one walk along the row, plus filling each gap once.

  • Time: O(n), where n is the number of dominoes. The main loop visits each of the n + 2 characters once. The gaps do not overlap, so all the filling loops together write at most n positions.
  • Space: O(n). The string s and the array result each hold n + 2 characters, and the returned string holds n.

Another way gives each domino a force: a push to the right from an 'R' on its left, and a push to the left from an 'L' on its right, each stronger the closer the pushed domino is and blocked by a domino pushed the other way. One pass from each side computes the forces, and the stronger push decides which way the domino falls, while equal pushes leave it upright. Candy uses the same pattern of one pass from each side.