← Home

853. Car Fleet

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
853

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 853. Car Fleet, the solution in this repository is mainly a greedy solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • WA
  • 18 / 44 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are carFleet.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(NlogN), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//WA
02//18 / 44 test cases passed.
03class Solution {
04public:
05    int carFleet(int target, vector<int>& position, vector<int>& speed) {
06        int N = position.size();
07        vector<pair<int, int>> pss(N);
08        int fleets = N; //every car is a fleet initially
09        
10        for(int i = 0; i < N; i++){
11            pss[i] = make_pair(position[i], speed[i]);
12        }
13        
14        sort(pss.begin(), pss.end());
15        
16        for(int i = 0; i < N; i++){
17            cout << "(" << pss[i].first << "," << pss[i].second << ") ";
18        }
19        cout << endl;
20        
21        double lastMeet = target;
22        
23        for(int i = N-2; i >= 0; i--){
24            if(pss[i].second > pss[i+1].second){
25                //current car's speed > the car in front of it
26                double t = (double)(pss[i+1].first - pss[i].first)/(pss[i].second - pss[i+1].second);
27                double meet = pss[i].first + t * pss[i].second;
28                cout << i << " and " << i+1 << "th car meet at: " << meet << endl;
29                if(meet <= lastMeet){
30                    fleets--;
31                    //ith car is blocked by i+1 th car
32                    pss[i].second = pss[i+1].second;
33                    cout << i << "th car's speed becomes " << pss[i].second << endl;
34                    lastMeet = meet;
35                }
36            }
37        }
38        
39        return fleets;
40    }
41};
42
43//use approach time to determine whether to merge two cars
44//Approach 1: Sort
45//Runtime: 56 ms, faster than 45.36% of C++ online submissions for Car Fleet.
46//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Car Fleet.
47//time: O(NlogN), space: O(N)
48class Solution {
49public:
50    int carFleet(int target, vector<int>& position, vector<int>& speed) {
51        int N = position.size();
52        vector<pair<int, double>> pts(N);
53        for(int i = 0; i < N; i++){
54            pts[i] = make_pair(position[i], (double)(target - position[i])/speed[i]);
55        }
56        sort(pts.begin(), pts.end());
57        
58        int ans = N; //we have N fleets initially
59        for(int i = N-2; i >= 0; i--){
60            //if car i will catch car (i+1) some time, we merge them
61            if(pts[i].second <= pts[i+1].second){
62                ans--;
63                //car i's speed is set to that of car i+1
64                pts[i].second = pts[i+1].second;
65            }
66        }
67        
68        return ans;
69    }
70};

Cost

Complexity

Time
O(NlogN), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.