KatInterview

Minimum Round-Trip Cost with Ordered Dates

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinggreedyprefix-minimumarray-optimization

Last updated

Tests prefix-minimum optimization to select two array indices under ordering constraints while minimizing their combined cost.

You are planning a round-trip journey. You have two arrays of equal length representing costs on different days:

  • depart: an array where depart[i] is the cost to leave on day i
  • return_costs: an array where return_costs[j] is the cost to come back on day j

You must choose a departure day i and a return day j such that you return strictly after you depart (i < j). The total cost of your trip is depart[i] + return_costs[j].

Find the minimum possible total cost and return the result as a list [total_cost, i, j] where i and j are the chosen days.

Tie-breaking: If multiple pairs (i, j) achieve the same minimum cost, return the lexicographically smallest pair. That is, prefer the smallest i first, and among those, the smallest j.

Edge case: If fewer than two days are available (making it impossible to satisfy i < j), return None.

Constraints

  • 0 ≤ len(depart) ≤ 10^5
  • len(depart) == len(return_costs)
  • -10^6 ≤ depart[i], return_costs[j] ≤ 10^6
  • All costs are integers

Examples

Example 1

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

Output: [3, 1, 2]

Example 2

Input: min_round_trip_cost([3, 1, 1, 5], [4, 2, 2, 1])

Output: [2, 1, 3]

Example 3

Input: min_round_trip_cost([-5, 2], [3, -4])

Output: [-9, 0, 1]

Hints

Hint 1

For each possible return day j, what is the best departure day you can pick from all earlier days?

Hint 2

Track the minimum departure cost seen so far as you scan through the days—this is a prefix minimum pattern.

Hint 3

Make sure to update your prefix minimum only after evaluating the current return day, so that you never pair day j with itself.