Final Departure From a Bouncing Convoy on a Road
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Find when the last vehicle leaves a segment and which one it is, when equal-speed vehicles reverse on contact, using pass-through equivalence and order preservation.
Bouncing Convoy
A straight road occupies the segment from coordinate 0 to coordinate road_length. There are n trucks on it, numbered 0 to n - 1. Truck i starts at coordinate starts[i] and always moves at a speed of exactly 1 unit per second.
The character headings[i] gives the initial direction of truck i:
'L'means it moves toward coordinate0.'R'means it moves toward coordinateroad_length.
Movement rules:
- When two trucks are at the same coordinate at the same moment, both reverse direction instantly and keep their speed. Collisions can happen at fractional times.
- A truck that reaches coordinate
0orroad_lengthleaves the road at once and plays no further part.
Find the moment the last truck leaves the road, and which truck it is. If several trucks leave at that latest moment, report the one with the smallest original index.
Input
road_length: integer, the length of the road.starts: list ofndistinct integers, the starting coordinates (in no particular order).headings: string of lengthnover{'L', 'R'};headings[i]is the initial direction of trucki.
Output
Return a tuple (last_time, truck_index), where last_time is the time at which the final truck leaves and truck_index is that truck's original 0-based index, with ties broken toward the smaller index. last_time is always an integer.
Constraints
1 <= road_length <= 10^91 <= n <= 10^5, wheren = len(starts) = len(headings)0 < starts[i] < road_length- All values in
startsare pairwise distinct. headings[i]is either'L'or'R'.
Examples
Example 1
Input: final_exit_on_road(10, [3, 7], 'RL')
Output: [7, 0]
Example 2
Input: final_exit_on_road(8, [2, 4, 6], 'LRR')
Output: [4, 1]
Hints
Hint 1
Simulating every bounce can take quadratic time. Ask what changes if two trucks simply drive through each other instead of bouncing: what stays the same, and what gets lost?
Hint 2
Treating trucks as passing through each other gives the correct multiset of exit times: a left-mover at p exits at time p, a right-mover at p exits at time road_length - p. What is missing is which real truck owns each event.
Hint 3
Real trucks never overtake one another, so their left-to-right order is fixed. If k trucks head left, the k leftmost trucks leave through 0 (in order of increasing time), and the rest leave through the right end, the rightmost one first. Match events to trucks accordingly, then take the maximum time with the smallest index on ties.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulating each bounce is too slow, since there can be on the order of n^2 collisions. Two observations avoid it.
1. Pass-through equivalence. When two equal-speed trucks meet and both reverse, the set of occupied positions over time is identical to the case where they pass through each other and only their labels are swapped. So imagine "ghost" trucks that ignore each other:
- A ghost starting at
pheading left leaves at coordinate0at timep. - A ghost starting at
pheading right leaves at coordinateroad_lengthat timeroad_length - p.
The multiset of exit events (time, end) for the real trucks equals that of the ghosts.
2. Order is preserved. Real trucks never overtake one another, so their left-to-right order is fixed. Let k be the number of left-heading trucks. Then exactly k exit events happen at coordinate 0, and they must belong to the k leftmost trucks, with the leftmost truck leaving first. Likewise the other n - k events happen at the right end, and the rightmost truck leaves first.
So:
- Sort the left-exit times ascending and assign them to the trucks in left-to-right order (the first
ktrucks). - Sort the right-exit times ascending and assign them to the remaining trucks starting from the rightmost and moving left.
Finally take the largest exit time, choosing the smallest original index among ties.
Why it is correct
The ghost picture gives exactly the right set of exit times at each end. The ordering argument forces a unique matching between those events and real trucks: a truck can leave through 0 only when no truck remains to its left, so left exits happen in left-to-right order, and symmetrically on the right. Exit times are always integers (p or road_length - p), even if collisions happen at half-integer moments.
Complexity
- Time:
O(n log n), dominated by sorting. - Space:
O(n).
Reference solution
from typing import List, Tuple
def final_exit_on_road(road_length: int, starts: List[int], headings: str) -> Tuple[int, int]:
n = len(starts)
# Truck indices ordered left to right; this order never changes.
order = sorted(range(n), key=lambda i: starts[i])
# Ghost (pass-through) exit times, each list ascending in time.
left_times = sorted(starts[i] for i in range(n) if headings[i] == 'L')
right_times = sorted(road_length - starts[i] for i in range(n) if headings[i] == 'R')
k = len(left_times)
exit_time = [0] * n
# The k leftmost trucks leave through 0, earliest event to leftmost truck.
for j in range(k):
exit_time[order[j]] = left_times[j]
# The remaining trucks leave through road_length, earliest event to rightmost truck.
for j in range(len(right_times)):
exit_time[order[n - 1 - j]] = right_times[j]
best_time, best_id = -1, -1
for i in range(n):
if exit_time[i] > best_time:
best_time, best_id = exit_time[i], i
return (best_time, best_id)