Minimum-Cost Daily Color Schedule
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Over a span of n consecutive days, you need to purchase one shirt per day in one of three colors: blue, green, or red. For each day i (0 <= i < n), the daily prices for those three options are given by blue_costs[i], green_costs[i], and red_costs[i].
Implement the following function:
def lowest_cost(blue_costs: list[int], green_costs: list[int], red_costs: list[int]) -> list[str]:
Your schedule must satisfy two requirements:
- Return a list of
nsingle-character strings where indexiis'b'(blue),'g'(green), or'r'(red), indicating which color is chosen on dayi. - Adjacent days must never use the same color: for every
iwith1 <= i < n, dayiand dayi - 1must have different colors. Reusing a color on non-adjacent days is allowed.
Choose the valid schedule whose sum of daily prices across all n days is minimized. Every test input is guaranteed to admit a unique minimum-cost valid schedule.
Examples
Example 1
Input: blue_costs = [6, 2, 7, 3], green_costs = [8, 5, 1, 9], red_costs = [3, 9, 6, 4]
Output: ['r', 'b', 'g', 'b']
Selecting red on day 0 (3), blue on day 1 (2), green on day 2 (1), and blue on day 3 (3) obeys the adjacent-day rule and achieves a total cost of 3 + 2 + 1 + 3 = 9. Every other valid four-day schedule costs strictly more than 9.
Example 2
Input: blue_costs = [4, 50], green_costs = [6, 50], red_costs = [2, 1]
Output: ['b', 'r']
Grabbing red on day 0 (2) looks cheaper initially, yet it blocks red on day 1 and forces a total of 2 + 50 = 52. Picking blue on day 0 (4) followed by red on day 1 (1) totals 5, beating all five other valid pairs (54, 56, 7, 52, and 52).
Example 3
Input: blue_costs = [8], green_costs = [11], red_costs = [6]
Output: ['r']
With only one day, there are no adjacent-day restrictions, so the cheapest single option ('r' at price 6) wins immediately.
Constraints
n == len(blue_costs) == len(green_costs) == len(red_costs)1 <= n <= 10^51 <= blue_costs[i], green_costs[i], red_costs[i] <= 10^4(all prices are integers, and the minimum total always fits within a 32-bit signed integer)- Each input has a unique valid color sequence with the minimum total cost.
Step-by-step walkthrough
Understand the problem and why greedy fails
On each day
dayfrom0ton - 1, we must buy one blue ('b'), green ('g'), or red ('r') shirt at priceblue_costs[day],green_costs[day], orred_costs[day]. Only one constraint links the days: we cannot buy the same color on two consecutive days (day - 1andday). Non-consecutive days may repeat colors freely. We need to return the unique list ofncolor letters ('b','g','r') that achieves the minimum total cost.Trying every valid sequence takes
3 * 2^(n - 1)possibilities—fine forn = 6, impossible forn = 10^5. What about a greedy rule that picks the cheapest allowed shirt on each day? Look at Example 2 (blue_costs = [4, 50],green_costs = [6, 50],red_costs = [2, 1]):Day 0 prices: blue = 4, green = 6, red = 2 Day 1 prices: blue = 50, green = 50, red = 1 Greedy pick: day 0 = 'r' (2) -> blocks 'r' on day 1 -> forced to pay 50 -> total 52! Optimal plan: day 0 = 'b' (4) -> leaves 'r' open -> day 1 = 'r' (1) -> total 5!Saving
2dollars on day 0 forced us to lose49dollars on day 1. Today's choice restricts tomorrow's options, so we cannot commit to a single color until we see how future days play out.Track the best total ending in each color
Ask a tiny question at day
day: How much of the past does daydayactually care about?It does not care what we wore two days ago or ten days ago—only yesterday's color (
day - 1), because that is the only color forbidden today! This observation gives us dynamic programming (solving a sequential problem by remembering only the compact summary of past states that affects future choices):For every day
dayand every colorcolorin{0 (blue), 1 (green), 2 (red)}, we store:min_total[day][color] = cheapest cumulative cost for days 0..day when we buy `color` on `day` Day 0 (base case): min_total[0][color] = price_by_color[color][0] Day >= 1 (transition): min_total[day][color] = price_by_color[color][day] + min(min_total[day - 1][prev] for prev != color)Instead of
3 * 2^(n - 1)sequences, we maintain just 3 numbers per day—3 * nvalues in total!Pick the best allowed previous color
Let us map colors to indices
0 -> 'b',1 -> 'g',2 -> 'r'in a constant listCOLORS = ["b", "g", "r"]so we can loop cleanly overrange(3).To compute the minimum over allowed colors without repeating
if/elsechains, we write a tiny helpercheapest_allowed_color(costs_row, forbidden_color). It returns whichever index in{0, 1, 2}(skippingforbidden_color) has the smallest cost incosts_row. Passingforbidden_color = -1skips nothing, which lets us reuse the exact same helper on the final day to pick the overall winner!# Color index mapping: 0 -> blue ('b'), 1 -> green ('g'), 2 -> red ('r') COLORS = ["b", "g", "r"] def cheapest_allowed_color(costs_row: List[int], forbidden_color: int) -> int: """Return the index in {0, 1, 2} != `forbidden_color` with the smallest value in `costs_row`. Passing `forbidden_color = -1` allows all three colors (used on the final day). """ best_color = -1 for color in range(3): if color == forbidden_color: continue if best_color == -1 or costs_row[color] < costs_row[best_color]: best_color = color return best_colorFill the DP table and record breadcrumbs
min_total[num_days - 1]gives us the minimum dollar amount, whereas the problem asks for the sequence of shirt colors.To reconstruct the exact choices effortlessly, whenever we pick
best_prevas yesterday's best color for(day, color), we also save a breadcrumbprev_color[day][color] = best_prev("if we end up wearingcoloronday, which color did we wear onday - 1?").Once the forward pass finishes:
- Find
current_color = cheapest_allowed_color(min_total[num_days - 1], -1)on the last day. - Walk backward from
day = num_days - 1down to1, recordingCOLORS[current_color]and stepping tocurrent_color = prev_color[day][current_color]. - Append day
0's color and reverse the list so it runs from day0to daynum_days - 1.
Because the problem guarantees a single unique minimum-cost sequence, the winning choice on the final day and every breadcrumb along the optimal path is uniquely determined.
def lowest_cost(blue_costs: list[int], green_costs: list[int], red_costs: list[int]) -> list[str]: num_days = len(blue_costs) if num_days == 0: return [] # price_by_color[color][day] gives the shirt price for `color` on `day` price_by_color = [blue_costs, green_costs, red_costs] # min_total[day][color] = cheapest cumulative cost for days 0..day ending with `color` on `day` # prev_color[day][color] = yesterday's color index that achieved min_total[day][color] min_total = [[0, 0, 0] for _ in range(num_days)] prev_color = [[-1, -1, -1] for _ in range(num_days)] # Phase 1: Base case on day 0 (no previous day to conflict with). for color in range(3): min_total[0][color] = price_by_color[color][0] # Phase 2: Fill days 1..num_days - 1, pairing each color today with the # cheapest allowed color from yesterday (any color except today's color). for day in range(1, num_days): for color in range(3): best_prev = cheapest_allowed_color(min_total[day - 1], color) min_total[day][color] = price_by_color[color][day] + min_total[day - 1][best_prev] prev_color[day][color] = best_prev # Phase 3: Reconstruct the unique optimal plan by starting at the cheapest # color on the last day and following `prev_color` breadcrumbs backward to day 0. current_color = cheapest_allowed_color(min_total[num_days - 1], -1) chosen_letters = [] for day in range(num_days - 1, 0, -1): chosen_letters.append(COLORS[current_color]) current_color = prev_color[day][current_color] chosen_letters.append(COLORS[current_color]) chosen_letters.reverse() return chosen_letters- Find
Trace Example 1 forward and backward
Let us trace Example 1:
blue_costs = [6, 2, 7, 3],green_costs = [8, 5, 1, 9],red_costs = [3, 9, 6, 4]. Each entry below showsmin_total (<- prev_color):Day | Prices [b, g, r] | Blue (0) | Green (1) | Red (2) ----+------------------+-----------------+-----------------+---------------- 0 | [6, 8, 3] | 6 | 8 | 3 1 | [2, 5, 9] | 2 + 3 = 5 (<-r)| 5 + 3 = 8 (<-r)| 9 + 6 = 15 (<-b) 2 | [7, 1, 6] | 7 + 8 = 15 (<-g)| 1 + 5 = 6 (<-b)| 6 + 5 = 11 (<-b) 3 | [3, 9, 4] | 3 + 6 = 9 (<-g)| 9 + 11= 20 (<-r)| 4 + 6 = 10 (<-g) Backward breadcrumb walk from Day 3: Day 3 winner: min of [9, 20, 10] is 9 at Blue ('b'), prev = Green Day 2: Green ('g'), prev = Blue Day 1: Blue ('b'), prev = Red Day 0: Red ('r') Collected backward: ['b', 'g', 'b', 'r'] -> reversed: ['r', 'b', 'g', 'b'] (total = 9)Notice why backward reconstruction from
min_totalis essential: on day 0 of Example 1,'r'(cost 3) happened to be cheapest, yet in Example 2 day 0's cheapest shirt'r'was a trap—only at the final daynum_days - 1do we know the true global minimum!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Color index mapping: 0 -> blue ('b'), 1 -> green ('g'), 2 -> red ('r') COLORS = ["b", "g", "r"] def cheapest_allowed_color(costs_row: List[int], forbidden_color: int) -> int: """Return the index in {0, 1, 2} != `forbidden_color` with the smallest value in `costs_row`. Passing `forbidden_color = -1` allows all three colors (used on the final day). """ best_color = -1 for color in range(3): if color == forbidden_color: continue if best_color == -1 or costs_row[color] < costs_row[best_color]: best_color = color return best_color def lowest_cost(blue_costs: list[int], green_costs: list[int], red_costs: list[int]) -> list[str]: num_days = len(blue_costs) if num_days == 0: return [] # price_by_color[color][day] gives the shirt price for `color` on `day` price_by_color = [blue_costs, green_costs, red_costs] # min_total[day][color] = cheapest cumulative cost for days 0..day ending with `color` on `day` # prev_color[day][color] = yesterday's color index that achieved min_total[day][color] min_total = [[0, 0, 0] for _ in range(num_days)] prev_color = [[-1, -1, -1] for _ in range(num_days)] # Phase 1: Base case on day 0 (no previous day to conflict with). for color in range(3): min_total[0][color] = price_by_color[color][0] # Phase 2: Fill days 1..num_days - 1, pairing each color today with the # cheapest allowed color from yesterday (any color except today's color). for day in range(1, num_days): for color in range(3): best_prev = cheapest_allowed_color(min_total[day - 1], color) min_total[day][color] = price_by_color[color][day] + min_total[day - 1][best_prev] prev_color[day][color] = best_prev # Phase 3: Reconstruct the unique optimal plan by starting at the cheapest # color on the last day and following `prev_color` breadcrumbs backward to day 0. current_color = cheapest_allowed_color(min_total[num_days - 1], -1) chosen_letters = [] for day in range(num_days - 1, 0, -1): chosen_letters.append(COLORS[current_color]) current_color = prev_color[day][current_color] chosen_letters.append(COLORS[current_color]) chosen_letters.reverse() return chosen_letters✅ Submit now — all tests should pass.
Intuition & how it works
Picture driving down a three-lane highway—a Blue lane, a Green lane, and a Red lane—where every mile has a toll booth in each lane, and a quirky traffic rule says you must switch lanes at every milepost. You want the cheapest trip from mile 0 to mile n - 1, along with the exact lane sequence you drove. Because the rule at mile day only cares which lane you occupied at mile day - 1 (and nothing earlier), we can use dynamic programming—solving a multi-step problem by keeping a small table of optimal subproblem answers rather than re-exploring overlapping histories. At each milepost and for each of the three lanes, we write down two things: the cheapest cumulative toll to reach that lane so far, and a breadcrumb (prev_color, also called a parent pointer) recording which of the other two lanes fed into it from yesterday.
Why do simpler ideas fail? Checking every valid color sequence branches 2 ways on every day after day 0, producing 3 * 2^(n - 1) sequences—astronomically slow when n = 100,000. Meanwhile, a shortsighted greedy strategy that grabs the cheapest allowed shirt each morning can paint itself into a corner: saving 1 dollar today by picking blue can force you to pay 100 dollars tomorrow when blue is off-limits.
Walk through Example 1 (blue_costs = [6, 2, 7, 3], green_costs = [8, 5, 1, 9], red_costs = [3, 9, 6, 4]):
- Day 0: Cumulative totals start at day 0's prices:
[b: 6, g: 8, r: 3]. - Day 1: Blue (
2) pairs with Red (3) ->5 (<-r); Green (5) pairs with Red (3) ->8 (<-r); Red (9) pairs with Blue (6) ->15 (<-b). Totals:[b: 5, g: 8, r: 15]. - Day 2: Blue (
7) pairs with Green (8) ->15 (<-g); Green (1) pairs with Blue (5) ->6 (<-b); Red (6) pairs with Blue (5) ->11 (<-b). Totals:[b: 15, g: 6, r: 11]. - Day 3 & backtrack: Blue (
3 + 6 = 9 <-g), Green (9 + 11 = 20 <-r), Red (4 + 6 = 10 <-g). Starting at Day 3's winner'b'(9) and following breadcrumbs backward ('b' -> 'g' -> 'b' -> 'r'), then reversing, recovers['r', 'b', 'g', 'b']with total cost9.
Complexity
Let n be the number of days (len(blue_costs)).
- Time: O(n). On day
0we initialize 3 cells; on each of the remainingn - 1days we fill 3 cells, and each cell checks the 2 other colors from the previous day (O(1)work per cell). Afterward, reconstructing the answer walks backward acrossndays once and reverses ann-element list, so every phase does a constant number of operations per day. - Space: O(n). Both
min_totalandprev_colorstorenrows of 3 integers (6 * nintegers total), and the returnedchosen_letterslist holdsnsingle-character strings. (Unlike the cost-only version of this problem, reconstructing the fulln-day sequence requires keepingO(n)history in memory.)
Edge cases
- Single day (
n = 1): The day1..n - 1loop does not run;cheapest_allowed_color(min_total[0], -1)directly picks the cheapest single shirt on day0. - Same color is cheapest on every single day: For
blue = [1, 1, 1], green = [5, 5, 5], red = [9, 9, 9], we cannot buy blue every day; the DP naturally alternates['b', 'g', 'b'](cost7) rather than['g', 'b', 'g'](cost11). - Color reused on non-adjacent days: Perfectly valid—only
day - 1anddayare compared, so patterns like['r', 'g', 'r', 'g', 'r']are found automatically. - Ties on unused branches: Even when the overall optimal sequence is unique, two colors can tie on a dead-end branch (for instance, in
blue = [1, 1], green = [1, 100], red = [100, 100], red on day 1 sees a tie between blue1and green1, while the unique global winner is['g', 'b']at cost2). Only the winning path's breadcrumbs are followed. - Maximum cumulative total: With
n <= 10^5andcost <= 10^4, every cell inmin_totalis at most10^9, fitting comfortably inside a standard 32-bit signed integer (<= 2,147,483,647) as well as Python's arbitrary-precisionint.
Common mistakes
- Choosing greedily day by day: Taking the cheapest valid shirt on day
iignores how blocking that color affects dayi + 1and fails on Example 2 (52instead of5). - Looking at single-day prices instead of cumulative DP totals when reconstructing: On
blue = [10, 10, 1], green = [10, 3, 10], red = [1, 2, 10], day 2 ends on'b'. If you pick day 1's color using day 1's raw price (red = 2 < green = 3) instead ofmin_total[1](green = 4 < red = 12), you reconstruct['b', 'r', 'b'](cost13) instead of['r', 'g', 'b'](cost5). Recordingprev_colorduring the forward pass prevents this bug completely. - Forgetting to ban today's color when picking yesterday's color: Taking
min(min_total[day - 1])across all three colors allows consecutive duplicates whenever one color dominates. - Reconstructing forward from
min_total[0]: Prefix totals only reveal the global winner at the last rowmin_total[n - 1]; starting atmin_total[0]degenerates right back into day-0 greedy. - Forgetting
.reverse()at the end (or callingchosen_letters.insert(0, ...)inside the loop): Backward traversal collects colors from dayn - 1down to day0, so the list must be reversed once (O(n))—never prepend withinsert(0, ...)on each step, which shifts elements inO(n^2)total time!
Alternative approaches
- Recompute predecessors from
min_totalwithoutprev_color: You can omit theprev_colorarray and, during the backward walk fromday = n - 1down to1, setcurrent_color = cheapest_allowed_color(min_total[day - 1], current_color). That saves half the table memory while running in the sameO(n)time, becausemin_total[day - 1]already contains the exact numbers the forward pass compared. - Suffix DP table (right-to-left): Define
suffix_best[day][color]as the minimum cost for daysday..n - 1when buyingcoloronday, filled backward fromday = n - 1down to0. Becausesuffix_best[0]holds the full trip totals at the start, you can read off the optimal sequence forward from day0ton - 1without reversing at the end.
Follow-up questions
- How would you keep the runtime linear in the number of days if there were k available colors instead of three? Scanning all
k - 1other colors for each of thekcells on a day would takeO(n * k^2)time. To bring it down to optimalO(n * k)time, scanmin_total[day - 1]once before fillingdayto find the smallest (min1_cost,min1_color) and second-smallest (min2_cost,min2_color) entries in that row: for every colorctoday exceptmin1_color, the best predecessor ismin1_color, and forc == min1_colorspecifically, the best predecessor ismin2_color—O(1)per cell! - If ties for the lowest total cost were possible and you had to break ties alphabetically, how would you adapt the algorithm? (Lexicographical order means standard dictionary/alphabetical order, comparing the first day where two sequences differ using
'b' < 'g' < 'r'.) Build the suffix DP tablesuffix_best[day][color]fromday = n - 1down to0. Then walk forward fromday = 0ton - 1: on day0, pick the earliest colorcin['b', 'g', 'r']whosesuffix_best[0][c]equalsmin(suffix_best[0]); on each subsequentday, among colorsc != yesterday_color, pick the earliest color whosesuffix_best[day][c]equalsmin(suffix_best[day][d] for d != yesterday_color). Choosing the alphabetically earliest tied color left-to-right guarantees the lexicographically smallest optimal plan. - How much extra memory would you need if the function only returned the minimum total cost rather than the full schedule? Since row
dayonly reads rowday - 1and we no longer need to walk backward through history, we can replace the entiren x 3tables with a single 3-element listprev_totals = [b, g, r]updated each day intocurr_totals, keepingO(n)time while shrinking auxiliary space fromO(n)toO(1).
Follow-up questions
- How would you keep the runtime linear in the number of days if there were k available colors instead of three?
- If ties for the lowest total cost were possible and you had to break ties alphabetically, how would you adapt the algorithm?
- How much extra memory would you need if the function only returned the minimum total cost rather than the full schedule?
Similar questions
- Minimum Remaining Count Under Equal-Tier Merges
- Next Greater Integer With Disjoint Digits
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance