838. Push Dominoes #1634
-
Topics: There are After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where:
Return a string representing the final state. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the final state of a line of dominoes after they have been pushed by forces from either the left or the right. The key challenge is to efficiently compute the effect of these forces without simulating each second step-by-step, which would be computationally expensive. Approach
Let's implement this solution in PHP: 838. Push Dominoes <?php
/**
* @param String $dominoes
* @return String
*/
function pushDominoes($dominoes) {
$n = strlen($dominoes);
$forceR = array_fill(0, $n, 1000000000);
$forceL = array_fill(0, $n, 1000000000);
// Left to right pass for R forces
$current_force = -1;
for ($i = 0; $i < $n; $i++) {
$c = $dominoes[$i];
if ($c == 'R') {
$current_force = 0;
} elseif ($c == 'L') {
$current_force = -1;
} else {
if ($current_force != -1) {
$current_force++;
$forceR[$i] = $current_force;
} else {
$forceR[$i] = 1000000000;
}
}
}
// Right to left pass for L forces
$current_force = -1;
for ($i = $n - 1; $i >= 0; $i--) {
$c = $dominoes[$i];
if ($c == 'L') {
$current_force = 0;
} elseif ($c == 'R') {
$current_force = -1;
} else {
if ($current_force != -1) {
$current_force++;
$forceL[$i] = $current_force;
} else {
$forceL[$i] = 1000000000;
}
}
}
// Build the result
$result = [];
for ($i = 0; $i < $n; $i++) {
$c = $dominoes[$i];
if ($c != '.') {
$result[] = $c;
} else {
$r = $forceR[$i];
$l = $forceL[$i];
if ($r < $l) {
$result[] = 'R';
} elseif ($l < $r) {
$result[] = 'L';
} else {
$result[] = '.';
}
}
}
return implode('', $result);
}
// Example usages
echo pushDominoes("RR.L") . "\n"; // Output: RR.L
echo pushDominoes(".L.R...LR..L..") . "\n"; // Output: LL.RR.LLRRLL..
?> Explanation:
This approach efficiently computes the final state in O(n) time by leveraging two passes and comparing the nearest forces, ensuring optimal performance even for large inputs. |
Beta Was this translation helpful? Give feedback.
We need to determine the final state of a line of dominoes after they have been pushed by forces from either the left or the right. The key challenge is to efficiently compute the effect of these forces without simulating each second step-by-step, which would be computationally expensive.
Approach