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.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- 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.
Use this to learn the idea, then write your own version.
1struct Car {2 int pos;3 int speed;4 double collisionTime;5 Car(int pos, int speed, double collisionTime)6 : pos(pos), speed(speed), collisionTime(collisionTime) {}7};8 9class Solution {10 public:11 vector<double> getCollisionTimes(vector<vector<int>>& cars) {12 vector<double> ans(cars.size());13 stack<Car> stack;14 15 for (int i = cars.size() - 1; i >= 0; --i) {16 const int pos = cars[i][0];17 const int speed = cars[i][1];18 while (!stack.empty() && (speed <= stack.top().speed ||19 getCollisionTime(stack.top(), pos, speed) >=20 stack.top().collisionTime))21 stack.pop();22 if (stack.empty()) {23 stack.emplace(pos, speed, INT_MAX);24 ans[i] = -1;25 } else {26 const double collisionTime = getCollisionTime(stack.top(), pos, speed);27 stack.emplace(pos, speed, collisionTime);28 ans[i] = collisionTime;29 }30 }31 32 return ans;33 }34 35 private:36 double getCollisionTime(const Car& car, int pos, int speed) {37 return (car.pos - pos) / (double)(speed - car.speed);38 }39};40