Leetcode Problem 2211. Count Collisions on a Road

2211. Count Collisions on a Road

Leetcode Solutions

Counting Collisions by Traversing and Skipping

  1. Initialize two pointers, left and right, to the start and end of the string respectively.
  2. Increment left until a car that is not moving left ('L') is found.
  3. Decrement right until a car that is not moving right ('R') is found.
  4. Initialize a variable collisions to 0 to count the number of collisions.
  5. Iterate over the string from left to right.
    • If the current car is moving right ('R'), increment a counter rightMovingCars.
    • If the current car is stationary ('S') or moving left ('L'), add rightMovingCars to collisions (plus one more if the car is moving left).
    • Reset rightMovingCars to 0 after each collision.
  6. Return the total number of collisions.
UML Thumbnail

Simulation with State Changes

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...