Problem solution · C++

Car Fleet II

Car Fleet II: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
40 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For Car Fleet II, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 40 lines of C++ from the credited upstream file 1776.cpp.
  • The implementation visibly relies on sequence storage.
  • 2 loop blocks detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCar Fleet II · C++C++
Use this to learn the idea, then write your own version.
struct Car {  int pos;  int speed;  double collisionTime;  Car(int pos, int speed, double collisionTime)      : pos(pos), speed(speed), collisionTime(collisionTime) {}}; class Solution { public:  vector<double> getCollisionTimes(vector<vector<int>>& cars) {    vector<double> ans(cars.size());    stack<Car> stack;     for (int i = cars.size() - 1; i >= 0; --i) {      const int pos = cars[i][0];      const int speed = cars[i][1];      while (!stack.empty() && (speed <= stack.top().speed ||                                getCollisionTime(stack.top(), pos, speed) >=                                    stack.top().collisionTime))        stack.pop();      if (stack.empty()) {        stack.emplace(pos, speed, INT_MAX);        ans[i] = -1;      } else {        const double collisionTime = getCollisionTime(stack.top(), pos, speed);        stack.emplace(pos, speed, collisionTime);        ans[i] = collisionTime;      }    }     return ans;  }  private:  double getCollisionTime(const Car& car, int pos, int speed) {    return (car.pos - pos) / (double)(speed - car.speed);  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗