Created
December 4, 2025 17:18
-
-
Save tatsuyax25/235ced6abf205b26f41e653b59e2442a to your computer and use it in GitHub Desktop.
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' de
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {string} directions | |
| * @return {number} | |
| */ | |
| var countCollisions = function(directions) { | |
| // Step 1: Convert string to array for easier handling | |
| let arr = directions.split(''); | |
| // Step 2: Remove cars that will never collide | |
| // Trim leading 'L' cars (they move left off the road) | |
| let i = 0; | |
| while (i < arr.length && arr[i] === 'L') { | |
| i++; | |
| } | |
| // Trim trailing 'R' cars (they move right off the road) | |
| let j = arr.length - 1; | |
| while (j >= 0 && arr[j] === 'R') { | |
| j--; | |
| } | |
| // Step 3: Count collisions in the remaining substring | |
| // Every 'L' or 'R' inside this range will eventually collide | |
| let collisions = 0; | |
| for (let k = i; k <= j; k++) { | |
| if (arr[k] === 'L' || arr[k] === 'R') { | |
| collisions++; | |
| } | |
| } | |
| return collisions; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment