KatInterview

Final Departure From a Bouncing Convoy on a Road

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingsimulation-shortcutghost-particles

Last 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 coordinate 0.
  • 'R' means it moves toward coordinate road_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 0 or road_length leaves 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 of n distinct integers, the starting coordinates (in no particular order).
  • headings: string of length n over {'L', 'R'}; headings[i] is the initial direction of truck i.

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^9
  • 1 <= n <= 10^5, where n = len(starts) = len(headings)
  • 0 < starts[i] < road_length
  • All values in starts are 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.