You are given a string dominoes
representing the initial state where:
'.'
represents a domino standing still.'L'
represents a domino that has been pushed to the left.'R'
represents a domino that has been pushed to the right.Return a string representing the final state after all dominoes have been pushed.
'.'
, 'L'
, and 'R'
.dominoes
by simulating the effect of domino pushes over time but do it in a single pass for efficiency.forces
to keep track of net forces applied on each position in dominoes
.'R'
).'L'
).'R'
).'L'
).'.'
).public class Solution {
public String pushDominoes(String dominoes) {
int n = dominoes.length();
int[] forces = new int[n];
// Traversing from left to right
int force = 0;
for (int i = 0; i < n; i++) {
if (dominoes.charAt(i) == 'R') {
force = n; // Reset the force to a high positive number
} else if (dominoes.charAt(i) == 'L') {
force = 0; // Reset the force to zero if 'L'
} else if (force > 0) {
force--; // Decrease the force for continuing 'R'
}
forces[i] += force;
}
// Traversing from right to left
force = 0;
for (int i = n - 1; i >= 0; i--) {
if (dominoes.charAt(i) == 'L') {
force = n; // Reset the force to a high negative number
} else if (dominoes.charAt(i) == 'R') {
force = 0; // Reset the force to zero if 'R'
} else if (force > 0) {
force--; // Decrease the force for continuing 'L'
}
forces[i] -= force;
}
// Construct final string based on net forces
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
if (forces[i] > 0) {
result.append('R');
} else if (forces[i] < 0) {
result.append('L');
} else {
result.append('.');
}
}
return result.toString();
}
}
dominoes
twice (once from left to right, and once from right to left), each in linear time.forces
array used to store the net forces applied to each position.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?