-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0838-push-dominoes.js
More file actions
49 lines (45 loc) · 1.33 KB
/
0838-push-dominoes.js
File metadata and controls
49 lines (45 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Push Dominoes
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var pushDominoes = function (dominoes) {
const dominoesLength = dominoes.length;
const resultingForces = new Array(dominoesLength).fill(0);
let rightwardForce = 0;
for (
let iteratorIndexForward = 0;
iteratorIndexForward < dominoesLength;
iteratorIndexForward++
) {
if (dominoes[iteratorIndexForward] === "R") {
rightwardForce = dominoesLength;
} else if (dominoes[iteratorIndexForward] === "L") {
rightwardForce = 0;
} else {
rightwardForce = Math.max(rightwardForce - 1, 0);
}
resultingForces[iteratorIndexForward] += rightwardForce;
}
let leftwardForce = 0;
for (
let iteratorIndexBackward = dominoesLength - 1;
iteratorIndexBackward >= 0;
iteratorIndexBackward--
) {
if (dominoes[iteratorIndexBackward] === "L") {
leftwardForce = dominoesLength;
} else if (dominoes[iteratorIndexBackward] === "R") {
leftwardForce = 0;
} else {
leftwardForce = Math.max(leftwardForce - 1, 0);
}
resultingForces[iteratorIndexBackward] -= leftwardForce;
}
const finalDominoesState = resultingForces.map((currentForceValue) => {
if (currentForceValue > 0) return "R";
if (currentForceValue < 0) return "L";
return ".";
});
return finalDominoesState.join("");
};