← Questions

Cheapest round trip from departure and return fares

0
MetaCodingLast asked Sep 2025

A coding interview question asked in Meta's technical phone screen, last asked Sep 2025. It tests arrays and greedy.

Two arrays give the fare for each day: D[i] to depart on day i and R[j] to return on day j. Choose a departure day and a strictly later return day so that the total fare is as low as possible.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • cheapest_trip(D: list[int], R: list[int]) -> list[int] — returns [min_cost, i, j] with 0 <= i < j < n. If n < 2, return [-1, -1, -1]. On ties, report the earliest return day, and the cheapest departure seen before it.

Example

cheapest_trip([5, 2, 8, 1], [10, 3, 6, 4])   ->  [6, 1, 3]       # depart day 1 (2), return day 3 (4)
cheapest_trip([3, 1, 4], [9, 9, 2])          ->  [3, 1, 2]
cheapest_trip([1], [1])                      ->  [-1, -1, -1]

Departing on day 3 for 1 is not an option in the first example: there is no later day to return.

Constraints

  • 1 <= n <= 10^5, and len(D) == len(R).
  • Fares are integers.

Clarifying questions

  • Must the return be strictly after the departure, or may it be the same day?
  • How should ties be reported?
  • Is there a minimum or maximum trip length?
  • Do you want the days or only the cost?

What a strong answer covers

  • One left-to-right pass that keeps the cheapest departure among days before j and combines it with R[j]. The same idea as one buy and one sell of a stock.
  • Updating the best total before folding D[j] into the running minimum, so a day is never both departure and return.
  • O(n) time, O(1) space, and why the O(n²) check of all pairs is unnecessary.
  • Edge cases: n < 2, ties, the cheapest departure on the last day.

Follow-ups

  • The trip must last at least m days.
  • The trip must last at most m days (a sliding-window minimum).
  • Several cities: depart from A to B, then B to C, then return.

Where it's asked

  • Meta · Technical phone screen · Last asked Sep 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

arrays · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding