Skip to content

Commit 60754b4

Browse files
committedMar 19, 2025
Add solution #838
1 parent 17034a4 commit 60754b4

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,7 @@
645645
835|[Image Overlap](./0835-image-overlap.js)|Medium|
646646
836|[Rectangle Overlap](./0836-rectangle-overlap.js)|Easy|
647647
837|[New 21 Game](./0837-new-21-game.js)|Medium|
648+
838|[Push Dominoes](./0838-push-dominoes.js)|Medium|
648649
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
649650
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
650651
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|

‎solutions/0838-push-dominoes.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* 838. Push Dominoes
3+
* https://leetcode.com/problems/push-dominoes/
4+
* Difficulty: Medium
5+
*
6+
* There are n dominoes in a line, and we place each domino vertically upright. In the beginning,
7+
* we simultaneously push some of the dominoes either to the left or to the right.
8+
*
9+
* After each second, each domino that is falling to the left pushes the adjacent domino on the
10+
* left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on
11+
* the right.
12+
*
13+
* When a vertical domino has dominoes falling on it from both sides, it stays still due to the
14+
* balance of the forces.
15+
*
16+
* For the purposes of this question, we will consider that a falling domino expends no additional
17+
* force to a falling or already fallen domino.
18+
*
19+
* You are given a string dominoes representing the initial state where:
20+
* - dominoes[i] = 'L', if the ith domino has been pushed to the left,
21+
* - dominoes[i] = 'R', if the ith domino has been pushed to the right, and
22+
* - dominoes[i] = '.', if the ith domino has not been pushed.
23+
*
24+
* Return a string representing the final state.
25+
*/
26+
27+
/**
28+
* @param {string} dominoes
29+
* @return {string}
30+
*/
31+
var pushDominoes = function(dominoes) {
32+
const forces = new Array(dominoes.length).fill(0);
33+
34+
let force = 0;
35+
for (let i = 0; i < dominoes.length; i++) {
36+
if (dominoes[i] === 'R') {
37+
force = dominoes.length;
38+
} else if (dominoes[i] === 'L') {
39+
force = 0;
40+
} else {
41+
force = Math.max(force - 1, 0);
42+
}
43+
forces[i] += force;
44+
}
45+
46+
force = 0;
47+
for (let i = dominoes.length - 1; i >= 0; i--) {
48+
if (dominoes[i] === 'L') {
49+
force = dominoes.length;
50+
} else if (dominoes[i] === 'R') {
51+
force = 0;
52+
} else {
53+
force = Math.max(force - 1, 0);
54+
}
55+
forces[i] -= force;
56+
}
57+
58+
return forces.map(f => {
59+
if (f > 0) return 'R';
60+
if (f < 0) return 'L';
61+
return '.';
62+
}).join('');
63+
};

0 commit comments

Comments
 (0)