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 n single-character strings where index i is 'b' (blue), 'g' (green), or 'r' (red), indicating which color is chosen on day i.
  • Adjacent days must never use the same color: for every i with 1 <= i < n, day i and day i - 1 must 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^5
  • 1 <= 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

  1. Understand the problem and why greedy fails

    On each day day from 0 to n - 1, we must buy one blue ('b'), green ('g'), or red ('r') shirt at price blue_costs[day], green_costs[day], or red_costs[day]. Only one constraint links the days: we cannot buy the same color on two consecutive days (day - 1 and day). Non-consecutive days may repeat colors freely. We need to return the unique list of n color letters ('b', 'g', 'r') that achieves the minimum total cost.

    Trying every valid sequence takes 3 * 2^(n - 1) possibilities—fine for n = 6, impossible for n = 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 2 dollars on day 0 forced us to lose 49 dollars 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.

  2. Track the best total ending in each color

    Ask a tiny question at day day: How much of the past does day day actually 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 day and every color color in {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 * n values in total!

  3. Pick the best allowed previous color

    Let us map colors to indices 0 -> 'b', 1 -> 'g', 2 -> 'r' in a constant list COLORS = ["b", "g", "r"] so we can loop cleanly over range(3).

    To compute the minimum over allowed colors without repeating if/else chains, we write a tiny helper cheapest_allowed_color(costs_row, forbidden_color). It returns whichever index in {0, 1, 2} (skipping forbidden_color) has the smallest cost in costs_row. Passing forbidden_color = -1 skips 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_color
    
  4. Fill 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_prev as yesterday's best color for (day, color), we also save a breadcrumb prev_color[day][color] = best_prev ("if we end up wearing color on day, which color did we wear on day - 1?").

    Once the forward pass finishes:

    1. Find current_color = cheapest_allowed_color(min_total[num_days - 1], -1) on the last day.
    2. Walk backward from day = num_days - 1 down to 1, recording COLORS[current_color] and stepping to current_color = prev_color[day][current_color].
    3. Append day 0's color and reverse the list so it runs from day 0 to day num_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
    
  5. 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 shows min_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_total is 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 day num_days - 1 do we know the true global minimum!

  6. 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]):

  1. Day 0: Cumulative totals start at day 0's prices: [b: 6, g: 8, r: 3].
  2. 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].
  3. 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].
  4. 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 cost 9.

Complexity

Let n be the number of days (len(blue_costs)).

  • Time: O(n). On day 0 we initialize 3 cells; on each of the remaining n - 1 days 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 across n days once and reverses an n-element list, so every phase does a constant number of operations per day.
  • Space: O(n). Both min_total and prev_color store n rows of 3 integers (6 * n integers total), and the returned chosen_letters list holds n single-character strings. (Unlike the cost-only version of this problem, reconstructing the full n-day sequence requires keeping O(n) history in memory.)

Edge cases

  • Single day (n = 1): The day 1..n - 1 loop does not run; cheapest_allowed_color(min_total[0], -1) directly picks the cheapest single shirt on day 0.
  • 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'] (cost 7) rather than ['g', 'b', 'g'] (cost 11).
  • Color reused on non-adjacent days: Perfectly valid—only day - 1 and day are 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 blue 1 and green 1, while the unique global winner is ['g', 'b'] at cost 2). Only the winning path's breadcrumbs are followed.
  • Maximum cumulative total: With n <= 10^5 and cost <= 10^4, every cell in min_total is at most 10^9, fitting comfortably inside a standard 32-bit signed integer (<= 2,147,483,647) as well as Python's arbitrary-precision int.

Common mistakes

  • Choosing greedily day by day: Taking the cheapest valid shirt on day i ignores how blocking that color affects day i + 1 and fails on Example 2 (52 instead of 5).
  • 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 of min_total[1] (green = 4 < red = 12), you reconstruct ['b', 'r', 'b'] (cost 13) instead of ['r', 'g', 'b'] (cost 5). Recording prev_color during 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 row min_total[n - 1]; starting at min_total[0] degenerates right back into day-0 greedy.
  • Forgetting .reverse() at the end (or calling chosen_letters.insert(0, ...) inside the loop): Backward traversal collects colors from day n - 1 down to day 0, so the list must be reversed once (O(n))—never prepend with insert(0, ...) on each step, which shifts elements in O(n^2) total time!

Alternative approaches

  • Recompute predecessors from min_total without prev_color: You can omit the prev_color array and, during the backward walk from day = n - 1 down to 1, set current_color = cheapest_allowed_color(min_total[day - 1], current_color). That saves half the table memory while running in the same O(n) time, because min_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 days day..n - 1 when buying color on day, filled backward from day = n - 1 down to 0. Because suffix_best[0] holds the full trip totals at the start, you can read off the optimal sequence forward from day 0 to n - 1 without 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 - 1 other colors for each of the k cells on a day would take O(n * k^2) time. To bring it down to optimal O(n * k) time, scan min_total[day - 1] once before filling day to find the smallest (min1_cost, min1_color) and second-smallest (min2_cost, min2_color) entries in that row: for every color c today except min1_color, the best predecessor is min1_color, and for c == min1_color specifically, the best predecessor is min2_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 table suffix_best[day][color] from day = n - 1 down to 0. Then walk forward from day = 0 to n - 1: on day 0, pick the earliest color c in ['b', 'g', 'r'] whose suffix_best[0][c] equals min(suffix_best[0]); on each subsequent day, among colors c != yesterday_color, pick the earliest color whose suffix_best[day][c] equals min(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 day only reads row day - 1 and we no longer need to walk backward through history, we can replace the entire n x 3 tables with a single 3-element list prev_totals = [b, g, r] updated each day into curr_totals, keeping O(n) time while shrinking auxiliary space from O(n) to O(1).

Follow-up questions

Similar questions

More Elevenlabs interview questions

All 3 Elevenlabs questions →