Find the Cheapest Valid Round Trip
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Implement `cheapest_round_trip(outbound, return_fares, min_gap)`.
`outbound[i]` is the fare for departing on day `i`, and `return_fares[j]` is the fare for returning on day `j`. Choose one departure and one return such that `j - i >= min_gap`, and return the minimum total fare.
The two fare arrays have the same length, `min_gap` is positive, and at least one valid pair exists. Target `O(n)` time and `O(n)` auxiliary space, or explain how to reduce the extra space while preserving linear time.
```hint Precompute future choices
For each day, record the cheapest return fare available from that day through the end of the array.
```
```hint Shift by the required stay
When considering departure day `i`, combine its fare with the suffix minimum beginning at `i + min_gap`, not at `i`.
```
### Discussion Extensions
- How does the solution simplify when only the minimum total cost is required rather than the chosen dates?
- How would you return deterministic dates when several pairs have the same minimum fare?
Quick Answer: Find the cheapest outbound and return fares subject to a minimum stay between the travel days. Use suffix minima to evaluate every valid departure in linear time, and discuss deterministic date selection and lower-space variants.
Implement cheapest_round_trip(outbound, return_fares, min_gap). outbound[i] is the fare to depart on day i and return_fares[j] is the fare to return on day j. Choose one pair with j - i >= min_gap and return the minimum total fare. At least one valid pair exists.
Constraints
- 2 <= outbound.length = return_fares.length <= 20.
- 1 <= min_gap < outbound.length.
- Every fare is an integer from 0 through 3,000,000,000.
- At least one departure and return pair satisfies j - i >= min_gap.
- Every valid total is within JavaScript's exact integer range.
Examples
Input: ([5, 3], [9, 4], 1)
Expected Output: 9
Explanation: The only valid pair departs on day 0 and returns on day 1.
Input: ([10, 1, 8, 4], [7, 9, 2, 6], 1)
Expected Output: 3
Explanation: Departure day 1 and return day 2 cost 1 + 2.
Hints
- For each departure day, only the cheapest return fare at least min_gap days later matters.
- Scanning departure days backward lets one rolling minimum represent the expanding valid return suffix.