You have n
dominoes in a line, and each domino is either upright ('.'
), tilting to the left ('L'
), or tilting to the right ('R'
). Given a string dominoes
representing the initial state, return a string representing the final state of the dominoes after pushing and toppling over.
R
and L
dominoes influence a single upright domino at the same time?L
and R
forces at the same time?'.'
, 'L'
, and 'R'
?Assuming the answers:
L
and R
at the same time, it remains upright.'.'
) that are bounded by L
and R
.R
on the left, the dominoes fall right.L
on the right, the dominoes fall left.R
and L
, balance the forces:
R
and L
remain upright.R
fall to the right, and those closer to L
fall to the left.#include <iostream>
#include <string>
#include <vector>
std::string pushDominoes(std::string dominoes) {
int n = dominoes.length();
std::vector<int> forces(n, 0);
int force = 0;
// Traverse left to right to apply forces from 'R'
for (int i = 0; i < n; ++i) {
if (dominoes[i] == 'R') {
force = n; // start with the maximum force
} else if (dominoes[i] == 'L') {
force = 0; // no force from right after an 'L'
} else {
force = std::max(force - 1, 0); // decrease force gradually
}
forces[i] += force;
}
force = 0;
// Traverse right to left to apply forces from 'L'
for (int i = n - 1; i >= 0; --i) {
if (dominoes[i] == 'L') {
force = n; // start with the maximum force
} else if (dominoes[i] == 'R') {
force = 0; // no force from left after an 'R'
} else {
force = std::max(force - 1, 0); // decrease force gradually
}
forces[i] -= force;
}
// Determine the final state of the dominoes
std::string result(n, '.');
for (int i = 0; i < n; ++i) {
if (forces[i] > 0) {
result[i] = 'R';
} else if (forces[i] < 0) {
result[i] = 'L';
} else {
result[i] = '.';
}
}
return result;
}
int main() {
std::string dominoes = ".L.R...LR..L..";
std::string result = pushDominoes(dominoes);
std::cout << "Result: " << result << std::endl;
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?