01/07/2021

[Java] Falling dominoes

Given an array representing dominoes, determine the final position of each piece. Array contains the following chars:
. = domino is standing still
R = domino is falling right
L = domino is falling left

The original problem used a string as input, however that is simply an array of characters, therefore the logic is the same.

Example:

R. = RR

R.L = R.L as center piece is being pushed from both sides

R..L = RRLL as center pieces can fall once but the get stuck in the middle

We can scan the input twice, from left to right and then right to left trcking partial outcomes in two arrays.

We then scan both arrays and determine the final position of a piece with the following cominations:

  • (. .) piece is standing still
  • (. R) (R R) piece is falling right
  • (. L) (L L) piece is falling left
  • (R L) piece is being pushed from both sides, leave it as it was in the input

We can get rid of the additional arrays altogether and just use the output array for all our operations. Still scan the array twice, first time left to right to determine which pieces would be falling right and we toggle a boolean to track whether pieces are falling right or not.
A piece falls right if it is AFTER another piece that also is falling right AND the NEXT piece is NOT falling left.


Second time we scan both input and partial result array right to left at the same time and repeat the process however we now have information about right falling pieces therefore we can determine the final domino position.
We use the same toggle to indicate whether pieces are falling left or not this time. We have the following cases:

  1. piece in input was standing still: if we are now falling left, look at the partial result, if that piece is marked as falling right we are pushing on it from both directions, leave it as it was in the input, otherwise mark it as falling left
  2. piece in input was falling right: toggle the falling switch to false
  3. piece in input was falling left: toggle the falling switch to true


We need to be careful in handling boundary cases for example when a piece that was standing still at the borders of the array is being pushed to fall, in that case no other force can balance it and we need to correctly update it to fall.

This provides a solution in O(N) time and constant space.

You can check my implementation of fallingDominoes on my Gist along with some tests in FallingDominoesJTests.

No comments:

Post a Comment

With great power comes great responsibility