KatInterview

Find Lowest Cost Ticket Pair Across Consecutive Days

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingarraysgreedyprefix-minimum

Last updated

Find the minimum combined cost of an outbound and return ticket where return happens strictly after departure.

You are given two integer lists of equal length $n$, representing flight prices over a sequence of days indexed from $0$ to $n-1$:

  • departure[i]: cost to leave on day $i$.
  • arrival[j]: cost to return on day $j$.

A valid itinerary requires leaving on some day $i$ and returning on some day $j$ strictly later ($j > i$). The total itinerary cost for this selection is departure[i] + arrival[j].

Find the minimum total cost among all valid combinations $(i, j)$ with $j > i$. If no valid itinerary can be formed (that is, when $n < 2$), return -1.

Constraints

  • $1 \le n \le 100{,}000$
  • len(departure) == len(arrival) == n
  • $0 \le \text{departure}[i], \text{arrival}[j] \le 10^9$

Examples

Example 1

Input: minimum_round_trip_cost([4, 2, 5, 1], [6, 3, 2, 7])

Output: 4

Example 2

Input: minimum_round_trip_cost([5], [5])

Output: -1

Hints

Hint 1

A brute force search checks all pairs (i, j) with i < j in O(n^2) time. Can you find the optimal outbound day for a fixed return day j in O(1)?

Hint 2

For any given return day j, the optimal outbound day is the one with the smallest departure cost among days 0 through j-1.

Hint 3

Track the running minimum departure cost as you iterate j from 1 to n-1. Be careful to combine arrival[j] with the running minimum *before* incorporating departure[j] into the minimum.