Minimum Cost For Tickets solution explained
Minimum Cost For Tickets asks for the cheapest way to cover a sorted list of travel days with 1-day, 7-day and 30-day passes. Let best[d] be the lowest cost to cover every travel day up to calendar day d: on a day you do not travel it equals best[d - 1], and on a travel day it is the cheapest of a 1-day pass after best[d - 1], a 7-day pass after best[d - 7] or a 30-day pass after best[d - 30], clamped at day 0. That runs in O(D) time for a calendar of D days, or O(n) over the travel days alone with two pointers.
By Evin JohnPublished 9 min read
The problem, restated
You plan to ride a train on certain days of the coming year. The days are given as numbers between 1 and 365, sorted, with no repeats. The ticket office sells three passes: one valid for a single day, one valid for 7 consecutive days and one valid for 30 consecutive days, each with its own price. A pass starts on the day you buy it. Find the least total you must spend so that every travel day falls inside some pass.
| Travel days | Prices | Cheapest total | One cheapest plan |
|---|---|---|---|
| [2, 3, 4, 9, 10, 31] | [3, 8, 20] | 17 | 7-day pass on day 4 (covers 4 to 10), 1-day passes on 2, 3 and 31 |
| [1, 2, 3, 4, 5, 6] | [2, 7, 30] | 7 | One 7-day pass instead of six singles at 12 |
| [5, 6, 7, 8, 9, 10, 11, 12, 40] | [4, 10, 25] | 18 | 7-day pass on day 5, singles on 12 and 40 |
| [1, 15, 29, 60] | [5, 20, 40] | 20 | Four singles; the trips are too far apart for longer passes |
| [10] | [6, 2, 9] | 2 | A 7-day pass, because it is the cheapest pass on offer |
| [1, 5, 6, 7, 8, 9, 10, 11] | [3, 8, 20] | 11 | A 1-day pass on day 1, then a 7-day pass on day 5 |
The last row shows why a greedy rule fails. Buying a 7-day pass on the first travel day, because several trips follow within the week, covers days 1 to 7 and leaves 8 to 11 needing another 8, for 16 in total. The best plan pays 3 for day 1 on its own and starts the week on day 5, for 11. The row with a single trip on day 10 is a different trap, for code that assumes prices rise with duration.
What the interviewer is testing
This is a clean test of whether you can define a DP state in words before writing it. The natural forward question, "which pass do I buy today?", leads to messy bookkeeping about how long the current pass lasts. The backward question, "what is the cheapest way to have everything up to today covered?", has three simple answers. Interviewers listen for that reframing, and then for correct handling of the window edge near the start of the year.
Follow-ups
- Any number of pass types with any durations. Loop over a list of (duration, price) pairs instead of three fixed terms.
- The calendar is huge but there are few trips. Index the DP by travel day instead of calendar day and move a pointer per pass type.
- Show which passes to buy. Record which option won at each travel day and walk back from the end.
- Passes start on fixed dates, like calendar months. The state stays the same, but each option looks back to the start of the fixed period rather than a fixed distance.
Brute force
Stand at the first uncovered travel day. You must buy something that covers it, and there is no reason to buy it any earlier, so try all three passes starting today, skip every travel day the pass covers, and recurse on the rest. That is up to 3^n branches for n travel days, but the only thing that changes between calls is the index of the first uncovered day, so memoizing on that index already gives a fast solution.
def min_cost_tickets_slow(days, prices, i=0):
if i == len(days):
return 0
best = float("inf")
for length, price in zip((1, 7, 30), prices):
j = i
while j < len(days) and days[j] < days[i] + length:
j += 1
best = min(best, price + min_cost_tickets_slow(days, prices, j))
return bestDynamic programming over the calendar
Let best[d] be the cheapest cost so that every travel day from 1 to d is covered. If day d is not a travel day, nothing new needs covering, so best[d] = best[d - 1]. If it is, some pass covers it, and you can assume the last pass you bought ends exactly on day d or later. Pretending it ends on day d is safe because a pass that runs past d costs the same. So the pass started on day d, d - 6 or d - 29, and everything before that start had to be covered already.
| Last pass bought | It covers | Cost |
|---|---|---|
| 1-day | day d only | best[d - 1] + price1 |
| 7-day | days d - 6 through d | best[max(0, d - 7)] + price7 |
| 30-day | days d - 29 through d | best[max(0, d - 30)] + price30 |
def min_cost_tickets(days, prices):
if not days:
return 0
travel = set(days)
last = days[-1]
best = [0] * (last + 1)
for d in range(1, last + 1):
if d not in travel:
best[d] = best[d - 1]
continue
best[d] = min(
best[d - 1] + prices[0],
best[max(0, d - 7)] + prices[1],
best[max(0, d - 30)] + prices[2],
)
return best[last]function minCostTickets(days, prices) {
if (days.length === 0) return 0;
const travel = new Set(days);
const last = days[days.length - 1];
const best = new Array(last + 1).fill(0);
for (let d = 1; d <= last; d++) {
if (!travel.has(d)) {
best[d] = best[d - 1];
continue;
}
best[d] = Math.min(
best[d - 1] + prices[0],
best[Math.max(0, d - 7)] + prices[1],
best[Math.max(0, d - 30)] + prices[2]
);
}
return best[last];
}Trace the first example, days [2, 3, 4, 9, 10, 31] with prices [3, 8, 20]. best[2] = 3, best[3] = 6, best[4] = min(9, 8, 20) = 8, because a week pass ending on day 4 covers days 1 to 4 from best[0] = 0. Days 5 to 8 copy 8. best[9] = min(11, best[2] + 8 = 11, 20) = 11, and best[10] = min(14, best[3] + 8 = 14, 20) = 14. That 14 is the week from 4 to 10 plus singles on 2 and 3. Days 11 to 30 copy 14, and best[31] = min(17, 22, best[1] + 20 = 20) = 17.
Indexing by travel day instead
If the calendar were millions of days long with only a few trips, a calendar-sized array would waste memory. Index by trip instead: cost[i] is the cheapest way to cover the first i trips. For each pass type keep a pointer to the first trip that a pass ending on trip i would not cover; because trips are sorted, each pointer only moves forward.
def min_cost_tickets_sparse(days, prices):
lengths = (1, 7, 30)
cost = [0] * (len(days) + 1)
start = [0, 0, 0] # first trip index still outside each pass window
for i, d in enumerate(days):
options = []
for k in range(3):
while days[start[k]] <= d - lengths[k]:
start[k] += 1
options.append(cost[start[k]] + prices[k])
cost[i + 1] = min(options)
return cost[len(days)]Here a pass of length L that ends on day d covers trips on days d - L + 1 through d, so the pointer skips every trip on or before d - L. cost[start[k]] is then the cheapest cover for the trips before the window.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Exhaustive search | O(3^n · n) in the worst case | O(n) stack |
| Memoized search on the first uncovered trip | O(n · 30) with the inner scan | O(n) |
| Calendar DP | O(D) | O(D) |
| Travel-day DP with pointers | O(n) | O(n) |
With D capped at 365, every approach except the exhaustive one is effectively instant. Say that out loud, then mention the sparse version as what you would use if the calendar grew.
Edge cases
- No travel days: cost 0.
- One travel day: the cheapest of the three prices, which may be a longer pass.
- Trips in the first week or month, where d - 7 or d - 30 goes below zero and must clamp to best[0].
- Long continuous runs, where 30-day passes back to back beat everything else.
- Very sparse trips, where singles win and the DP should not reach for long passes.
Common mistakes
- Greedy choices such as "buy a week pass on a trip if more trips follow within 7 days". The last example row breaks it.
- Off by one on the window: a 7-day pass ending on day d covers d - 6 to d, so the look-back is best[d - 7], not best[d - 6].
- Forgetting to copy best[d - 1] on non-travel days, which leaves zeros in the middle of the table.
- Skipping the clamp, so Python silently reads best[-3] from the end of the list.
- Assuming the 1-day pass is cheapest and returning early for a single trip.
How to explain it out loud
Fictional example
- Candidate
- Deciding which pass to buy going forward is awkward, so I will ask a backward question: what is the cheapest way to have every trip up to day d covered?
- Candidate
- If I do not travel on day d, the answer is the same as for d minus 1. If I do, the last pass I bought covers d, and I can assume it ends on d, so it started 1, 7 or 30 days back. I add its price to the answer from just before it started.
- Candidate
- The calendar is at most 365 days, so one array and one pass is linear in the calendar. If the calendar were huge, I would index by trip and keep a pointer per pass type instead.
Related problems
Coin Change II also builds an answer from a small menu of options per step, but counts ways instead of minimizing. Perfect Squares is another minimum-cost DP where each value looks back at a few earlier ones. Best Time to Buy and Sell Stock III is a day-by-day DP too, with states for how many trades you have used.
Practicing with Natively
The step worth drilling is saying the state definition in one sentence before you write any loop. When you practice on Mac or Windows, Natively can read the problem from a screenshot and offer a solution outline to check against yours after your own attempt, and the transcript of a mock round shows whether you explained the window look-back clearly. More on the AI interview assistant.
Questions people ask
How do you solve Minimum Cost For Tickets?
Let best[d] be the cheapest cover for all trips up to day d. On a non-travel day best[d] = best[d - 1]; on a travel day take the minimum of best[d - 1] plus the 1-day price, best[d - 7] plus the 7-day price and best[d - 30] plus the 30-day price, clamping negative indexes to 0.
Why doesn't a greedy approach work for Minimum Cost For Tickets?
Where a pass starts changes which later trips it covers, and a cheaper-looking choice now can force extra passes later. The DP compares every way the last pass could end on each day.
What is the time complexity of Minimum Cost For Tickets?
O(D) time and memory for a calendar of D days, which is at most 365. Indexing by travel day with one pointer per pass type makes it O(n) for n trips.
Can a longer pass be cheaper than a shorter one?
Yes, nothing in the problem forbids it, so always take the minimum of all three options instead of assuming prices rise with duration.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
