Top 150 InterviewЛегко

Car Fleet

Detailed guide and Python implementation for the 'Car Fleet' problem.

Постановка задачи

Легко

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 arrays 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 (they are assumed to be at the same position).

A car fleet is some non-empty set of cars driving at the same position and same speed. A single car is also a car fleet.

Return the number of car fleets that will arrive at the destination.

Write a function carFleet(target: int, position: List[int], speed: List[int]) -> int.

Ограничения
  • n == len(position) == len(speed)
  • 1 <= n <= 10^5
  • 0 < target <= 10^6
  • 0 <= position[i] < target
  • 0 < speed[i] <= 10^6
  • All positions are unique

Примеры

Example 1
Input
target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]
Output
3
Explanation

Cars at positions 10 and 8: car at 8 catches car at 10 (both arrive at time 1), forming 1 fleet. Car at 0: arrives at time 12. Car at 5: arrives at time 7. Car at 3: arrives at time 3, catches car at 5 at time 7, but car at 5 arrives at 7 too. Cars at 3 and 5 form a fleet. Total: 3 fleets.

Example 2
Input
target = 10, position = [3], speed = [3]
Output
1
Explanation

Only one car, so one fleet.

Example 3
Input
target = 100, position = [0, 2, 4], speed = [4, 2, 1]
Output
1
Explanation

All cars eventually form a single fleet.

Need a Hint?
Consider using Stack-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Готовы решить?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Открыть в редакторе
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Рекомендуемые ресурсы Python

Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.

Учебник по Python

Циклы Python

Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.

Посмотреть ресурс
Практическое руководство

Как отсортировать список в Python

Узнайте, как сортировать список в Python с помощью метода sort() и функции sorted(). Ознакомьтесь с примерами пользовательской сортировки ключей и обратного порядка.

Посмотреть ресурс
Шпаргалка

Шпаргалка по строковым методам Python

Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.

Посмотреть ресурс
Сравнение языков

Python против JavaScript: какой язык программирования лучше?

Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.

Посмотреть ресурс