-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0853_car_fleet.html
More file actions
450 lines (382 loc) · 16.5 KB
/
0853_car_fleet.html
File metadata and controls
450 lines (382 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Car Fleet - LeetCode 853</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#853</span> Car Fleet</h1>
<p>Cars on a road heading to a target. Faster cars can't pass slower ones, they form "fleets." Count how many fleets reach the destination!</p>
<div class="problem-meta">
<span class="meta-tag">📚 Stack</span>
<span class="meta-tag">🔢 Sorting</span>
<span class="meta-tag">⏱️ O(n log n)</span>
</div>
<div class="file-ref">
📄 Python: <a href="../python/0853_car_fleet/0853_car_fleet.py">0853_car_fleet.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>💡 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Problem:</strong> Cars can't pass each other on a single-lane road. Faster cars behind slow down to match slower cars ahead.</li>
<li><strong>Fleet:</strong> Cars that catch up and travel together at the same speed.</li>
<li><strong>Key insight:</strong> Process cars from closest to target first. A car forms a new fleet if it takes longer to reach target than any car ahead.</li>
<li><strong>Time to target:</strong> (target - position) / speed</li>
<li><strong>Logic:</strong> If a car takes MORE time than the max time seen so far, it can't catch up → new fleet!</li>
<li><strong>If LESS time:</strong> It would catch up and merge with the fleet ahead.</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="info-box">
Target = 12 miles
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to see how cars form fleets
</div>
<div class="svg-container">
<svg id="roadSvg" width="800" height="200"></svg>
</div>
<div class="array-section">
<div class="array-label">Cars (sorted by position, closest to target first):</div>
<div id="carsTable" style="overflow-x: auto;"></div>
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Current Max Time</div>
<div class="variable-value" id="maxTimeVal">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Fleet Count</div>
<div class="variable-value" id="fleetVal">0</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Car Fleet
Problem from LeetCode: https://leetcode.com/problems/car-fleet/
Description:
There are n cars going to the same destination along a one-lane road. The destination is target miles away.
You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).
A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).
A car fleet is some non-empty set of cars driving at the same speed. Note that a single car is also a car fleet.
If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.
Return the number of car fleets that will arrive at the destination.
Example 1:
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting at 12.
The car starting at 0 does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting at 6. The fleet moves at speed 1 until it reaches target.
Note that no other cars meet these fleets before the destination, so the answer is 3.
Example 2:
Input: target = 10, position = [3], speed = [3]
Output: 1
Explanation: There is only one car, hence there is only one fleet.
Example 3:
Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
Explanation:
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting at 4. The fleet moves at speed 2.
Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting at 6. The fleet moves at speed 1 until it reaches target.
Constraints:
n == position.length == speed.length
1 <= n <= 10^5
0 <= position[i] < target
All the values of position are unique.
0 < speed[i] <= 10^6
1 <= target <= 10^6
"""
class Solution:
def car_fleet(self, target: int, position: List[int], speed: List[int]
) ->int:
"""
Determine the number of car fleets that will arrive at the target.
Args:
target: The target destination (finish line)
position: Position of each car on the road (0 is the start, target is the end)
speed: Speed of each car in distance per hour
Returns:
int: The number of car fleets that will arrive at the target
"""
n = len(position)
cars = []
for i in range(n):
time_to_target = (target - position[i]) / speed[i]
cars.append([position[i], time_to_target])
cars.sort(reverse=True)
fleets = 0
current_max_time = 0
for _, time in cars:
if time > current_max_time:
fleets += 1
current_max_time = time
return fleets
def carFleet_stack(self, target: int, position: List[int], speed: List[int]
) ->int:
"""
Determine the number of car fleets using a stack approach.
Args:
target: The target destination
position: Position of each car
speed: Speed of each car
Returns:
int: The number of car fleets
"""
cars = sorted(zip(position, speed))
times = [((target - p) / s) for p, s in cars]
result = 0
while times:
current_time = times.pop()
if not times or current_time > times[-1]:
result += 1
return result
def carFleet_simplified(self, target: int, position: List[int], speed:
List[int]) ->int:
"""
Determine the number of car fleets with simplified code.
Args:
target: The target destination
position: Position of each car
speed: Speed of each car
Returns:
int: The number of car fleets
"""
pairs = [(p, (target - p) / s) for p, s in zip(position, speed)]
pairs.sort()
fleets = 0
current_time = 0
for _, time in reversed(pairs):
if time > current_time:
fleets += 1
current_time = time
return fleets
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
target1 = 12
position1 = [10, 8, 0, 5, 3]
speed1 = [2, 4, 1, 1, 3]
result1 = solution.car_fleet(target1, position1, speed1)
print(f"Example 1: {result1}") # Expected: 3
# Example 2
target2 = 10
position2 = [3]
speed2 = [3]
result2 = solution.car_fleet(target2, position2, speed2)
print(f"Example 2: {result2}") # Expected: 1
# Example 3
target3 = 100
position3 = [0, 2, 4]
speed3 = [4, 2, 1]
result3 = solution.car_fleet(target3, position3, speed3)
print(f"Example 3: {result3}") # Expected: 1
</pre>
</div>
</div>
</div>
<script>
const target = 12;
const positions = [10, 8, 0, 5, 3];
const speeds = [2, 4, 1, 1, 3];
let cars = [];
let sortedCars = [];
let currentCarIndex = 0;
let currentMaxTime = 0;
let fleets = 0;
let phase = 'init';
let autoInterval = null;
function init() {
cars = positions.map((pos, i) => ({
position: pos,
speed: speeds[i],
time: (target - pos) / speeds[i],
fleet: null
}));
sortedCars = [...cars].sort((a, b) => b.position - a.position);
currentCarIndex = 0;
currentMaxTime = 0;
fleets = 0;
drawRoad();
renderCarsTable();
document.getElementById('maxTimeVal').textContent = '0';
document.getElementById('fleetVal').textContent = '0';
}
function drawRoad() {
const svg = d3.select("#roadSvg");
svg.selectAll("*").remove();
const roadY = 100;
const roadStart = 50;
const roadEnd = 750;
const scale = (roadEnd - roadStart) / target;
// Draw road
svg.append("line")
.attr("x1", roadStart)
.attr("y1", roadY)
.attr("x2", roadEnd)
.attr("y2", roadY)
.attr("stroke", "#333")
.attr("stroke-width", 4);
// Draw target
svg.append("rect")
.attr("x", roadEnd - 5)
.attr("y", roadY - 30)
.attr("width", 10)
.attr("height", 60)
.attr("fill", "#f44336");
svg.append("text")
.attr("x", roadEnd)
.attr("y", roadY - 40)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("TARGET");
// Draw cars
const fleetColors = ['#667eea', '#11998e', '#f093fb', '#ff9800', '#4caf50'];
sortedCars.forEach((car, i) => {
const x = roadStart + car.position * scale;
const color = car.fleet !== null ? fleetColors[car.fleet % fleetColors.length] : '#999';
// Car body
svg.append("rect")
.attr("x", x - 15)
.attr("y", roadY - 25)
.attr("width", 30)
.attr("height", 20)
.attr("rx", 5)
.attr("fill", color)
.attr("stroke", i === currentCarIndex && phase === 'processing' ? "#f44336" : "none")
.attr("stroke-width", 3);
// Car info
svg.append("text")
.attr("x", x)
.attr("y", roadY + 30)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.text(`pos:${car.position}`);
svg.append("text")
.attr("x", x)
.attr("y", roadY + 42)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.text(`spd:${car.speed}`);
svg.append("text")
.attr("x", x)
.attr("y", roadY + 54)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.text(`t:${car.time.toFixed(1)}`);
});
// Position markers
for (let p = 0; p <= target; p += 2) {
const x = roadStart + p * scale;
svg.append("text")
.attr("x", x)
.attr("y", roadY + 70)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#666")
.text(p);
}
}
function renderCarsTable() {
const container = document.getElementById('carsTable');
let html = '<table class="problem-table"><tr><th>Order</th><th>Position</th><th>Speed</th><th>Time to Target</th><th>Fleet</th></tr>';
sortedCars.forEach((car, i) => {
const highlight = i === currentCarIndex && phase === 'processing' ? 'style="background: #fff3e0;"' : '';
const fleetDisplay = car.fleet !== null ? `Fleet ${car.fleet + 1}` : '-';
html += `<tr ${highlight}>
<td>${i + 1}</td>
<td>${car.position}</td>
<td>${car.speed}</td>
<td>${car.time.toFixed(2)}</td>
<td>${fleetDisplay}</td>
</tr>`;
});
html += '</table>';
container.innerHTML = html;
}
function step() {
if (phase === 'init') {
phase = 'processing';
document.getElementById('statusMessage').textContent =
'Processing cars from closest to target (position 10) to farthest...';
}
if (phase === 'processing') {
if (currentCarIndex >= sortedCars.length) {
phase = 'done';
document.getElementById('statusMessage').textContent =
`✅ Done! Total fleets: ${fleets}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const car = sortedCars[currentCarIndex];
if (car.time > currentMaxTime) {
// New fleet!
car.fleet = fleets;
fleets++;
currentMaxTime = car.time;
document.getElementById('statusMessage').textContent =
`Car at position ${car.position}: time=${car.time.toFixed(2)} > maxTime=${(currentMaxTime === car.time ? 0 : currentMaxTime).toFixed(2)} → NEW FLEET #${fleets}!`;
} else {
// Joins previous fleet
car.fleet = fleets - 1;
document.getElementById('statusMessage').textContent =
`Car at position ${car.position}: time=${car.time.toFixed(2)} ≤ maxTime=${currentMaxTime.toFixed(2)} → Catches up & joins Fleet #${fleets}`;
}
document.getElementById('maxTimeVal').textContent = currentMaxTime.toFixed(2);
document.getElementById('fleetVal').textContent = fleets;
drawRoad();
renderCarsTable();
currentCarIndex++;
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1500);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to see how cars form fleets';
init();
}
init();
</script>
</body>
</html>