Minimum Schedule Days With Cooldown

Medium · Coding & Algorithms · Data Engineer · Technical Screen

Problem Statement

An assembly line processes a fixed queue of item category IDs given in products from index 0 to len(products) - 1, completing at most one item per calendar day starting on Day 1.

Every item category shares a uniform reset requirement governed by the non-negative integer space:

  • Items cannot be reordered; products[i] must finish strictly before products[i + 1].
  • At most one item may finish on any single day.
  • Once category c finishes on day d, at least space complete intervening days must pass before another item of category c can run—making day d + space + 1 the earliest legal repeat day for category c.
  • While category c is resetting, the line may run the next queued item if its own category is ready; if the next queued item is still resetting, the line remains idle until that category becomes ready.

Implement min_days(products, space) to return the earliest calendar day on which the entire queue finishes (0 when products is empty).

def min_days(products: List[int], space: int) -> int:

Examples

Example 1

  • Input: products = [4, 7, 4, 9, 7, 9], space = 3
  • Output: 10
  • Explanation:
    • Day 1: category 4
    • Day 2: category 7
    • Days 3–4: idle (category 4 ran on Day 1 and requires 3 full intervening days, unlocking on Day 1 + 3 + 1 = 5)
    • Day 5: category 4
    • Day 6: category 9
    • Day 7: category 7 (unlocked on Day 2 + 3 + 1 = 6, so no extra wait is needed)
    • Days 8–9: idle (category 9 ran on Day 6 and unlocks on Day 6 + 3 + 1 = 10)
    • Day 10: category 9

Example 2

  • Input: products = [2, 5, 8, 2], space = 2
  • Output: 4
  • Explanation: Categories 2, 5, and 8 run on Days 1, 2, and 3. By Day 4, two full intervening days (Days 2 and 3) have already elapsed since Day 1, so the second 2 runs immediately on Day 4 with zero idle days.

Constraints

  • 0 <= len(products) <= 10^5
  • -10^9 <= products[i] <= 10^9
  • 0 <= space <= 10^9

Step-by-step walkthrough

  1. Understand the calendar rules and reset gap

    We process products strictly in index order, completing at most one item per day starting on Day 1 (returning 0 when products is empty). Whenever category c runs on Day d, space complete intervening days must separate it from the next copy of category c:

    Category 4 runs on Day 1 with space = 3:
    
    Day 1        Day 2       Day 3       Day 4       Day 5
    [ run 4 ]    [ gap #1 ]  [ gap #2 ]  [ gap #3 ]  [ earliest repeat of 4 ]
                                                     ^
                                                     1 + 3 + 1 = Day 5
    

    During those intervening days (Days 2, 3, and 4 above), the line can run the next item in products if its own category is unlocked; otherwise the line sits idle.

  2. Why ticking one day at a time is too slow

    A literal calendar loop increments day = 1, 2, 3, ..., checking on each day whether the front queued item is unlocked and idling if not.

    That works when space is tiny, yet space can reach 10^9. On products = [7, 7] with space = 1_000_000_000:

    • Day 1: run 7.
    • Days 2 through 1_000_000_001: burn a billion idle loop iterations!
    • Day 1_000_000_002: run the second 7.

    Instead of stepping across idle days in O(n * space) time, we can compute the exact unlock day and jump directly there in O(1).

  3. Greedy choice: run every item as early as legal

    Suppose all items before index i are scheduled and item i - 1 landed on current_day. What bounds the day d of the current category?

    1. Sequential capacity: Only one item finishes per day, requiring d >= current_day + 1.
    2. Category reset: If category appeared earlier, only its most recent day last_run_day[category] restricts us (any older occurrence unlocked even earlier), requiring d >= last_run_day[category] + space + 1.

    Picking max(current_day + 1, unlock_day) schedules the current item on its earliest legal day. Could inserting an unnecessary extra idle day ever shorten the finish time of later items? Never—pushing today's item later only raises current_day + 1 and last_run_day[category] + space + 1, which can never let any subsequent item run sooner.

  4. Store each category's latest day in a dictionary

    Keep a dictionary last_run_day mapping each seen category to its latest 1-based calendar day, alongside current_day = 0.

    last_run_day: Dict[int, int] = {}
    current_day = 0
    
    for category in products:
        next_legal_day = current_day + 1
        if category in last_run_day:
            unlock_day = last_run_day[category] + space + 1
            if next_legal_day < unlock_day:
                next_legal_day = unlock_day
    
        current_day = next_legal_day
        last_run_day[category] = current_day
    

    When products is empty, the loop never executes and current_day remains 0.

  5. Trace Example 1 step by step

    Let's trace products = [4, 7, 4, 9, 7, 9] with space = 3 (space + 1 = 4):

    Start: current_day = 0, last_run_day = {}
    
    Index 0 (category = 4):
      next_legal_day = 0 + 1 = 1 (unseen)
      current_day = 1, last_run_day = {4: 1}
    
    Index 1 (category = 7):
      next_legal_day = 1 + 1 = 2 (unseen)
      current_day = 2, last_run_day = {4: 1, 7: 2}
    
    Index 2 (category = 4):
      next_legal_day = 2 + 1 = 3, unlock_day = 1 + 4 = 5
      3 < 5 -> leap to Day 5 (Days 3 and 4 skipped as idle!)
      current_day = 5, last_run_day = {4: 5, 7: 2}
    
    Index 3 (category = 9):
      next_legal_day = 5 + 1 = 6 (unseen)
      current_day = 6, last_run_day = {4: 5, 7: 2, 9: 6}
    
    Index 4 (category = 7):
      next_legal_day = 6 + 1 = 7, unlock_day = 2 + 4 = 6
      7 < 6 is False -> run immediately on Day 7
      current_day = 7, last_run_day = {4: 5, 7: 7, 9: 6}
    
    Index 5 (category = 9):
      next_legal_day = 7 + 1 = 8, unlock_day = 6 + 4 = 10
      8 < 10 -> leap to Day 10 (Days 8 and 9 skipped as idle!)
      current_day = 10, last_run_day = {4: 5, 7: 7, 9: 10}
    
    Return: 10
    
  6. Complete solution

    Putting everything together gives the full O(n) solution.

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def min_days(products: List[int], space: int) -> int:
        # last_run_day: maps category ID -> most recent 1-based day it ran (e.g. {4: 5, 7: 2})
        last_run_day: Dict[int, int] = {}
        # current_day: 1-based day of the most recently completed item (0 before any item runs)
        current_day = 0
    
        # Phase 1: Assign each queued item in strict index order to its earliest legal day.
        for category in products:
            # Constraint 1 (single-item capacity): today must follow the previous item's day.
            next_legal_day = current_day + 1
    
            # Constraint 2 (reset gap): `space` full intervening days after day `d` block d+1 .. d+space,
            # so the category unlocks on day d + space + 1 (not d + space).
            if category in last_run_day:
                unlock_day = last_run_day[category] + space + 1
                if next_legal_day < unlock_day:
                    next_legal_day = unlock_day
    
            # Phase 2: Leap directly to next_legal_day in O(1) (skipping any idle days) and record it.
            current_day = next_legal_day
            last_run_day[category] = current_day
    
        return current_day
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a stamping press fed by a single-file conveyor belt of metal parts, where each die (category) needs space full days to cool before stamping that same die shape again. Whenever the next part's die is cool, stamping it right away is optimal—voluntarily idling today only shifts today's part and every part behind it onto later calendar days. That structure lets us apply a greedy algorithm — a strategy that commits to the earliest valid option at each step without backtracking — paired with a hash map (Python dict, an O(1) average-time key-value lookup table) recording the latest day each category ran.

Why does naive day-by-day simulation fall short? Stepping day = 1, 2, 3, ... one day at a time works on small test cases, yet on products = [7, 7] with space = 1,000,000,000 it spends a billion iterations ticking across empty days (O(n * space) time). Looking up last_run_day[category] and jumping straight to max(current_day + 1, last_run_day[category] + space + 1) skips arbitrarily long idle stretches in O(1) arithmetic.

Let's trace Example 1 (products = [4, 7, 4, 9, 7, 9], space = 3, so repeats add + 4):

Idx 0 (cat 4): next = 1, unseen           -> Day 1  | last_run_day = {4: 1}
Idx 1 (cat 7): next = 2, unseen           -> Day 2  | last_run_day = {4: 1, 7: 2}
Idx 2 (cat 4): next = 3, unlock = 1+4 = 5 -> Day 5  | last_run_day = {4: 5, 7: 2} (Days 3-4 idle)
Idx 3 (cat 9): next = 6, unseen           -> Day 6  | last_run_day = {4: 5, 7: 2, 9: 6}
Idx 4 (cat 7): next = 7, unlock = 2+4 = 6 -> Day 7  | last_run_day = {4: 5, 7: 7, 9: 6}
Idx 5 (cat 9): next = 8, unlock = 6+4 = 10-> Day 10 | last_run_day = {4: 5, 7: 7, 9: 10} (Days 8-9 idle)

Final day = 10

Complexity

Let n be len(products) and u be the count of distinct category IDs (u <= n).

  • Time: O(n) on average. We scan the n items once, performing one O(1) average-time dictionary lookup, constant-time integer arithmetic, and one O(1) dictionary update per item, completely independent of space.
  • Space: O(u). last_run_day holds at most one entry per distinct category (O(u) <= O(n)).

Edge cases

  • Empty products ([]): current_day starts at 0 and the loop skips directly to return 0.
  • Zero reset gap (space = 0): last_run_day[category] + 0 + 1 <= current_day + 1, so zero idle days occur and the answer equals len(products).
  • All unique categories ([1, 2, 3, 4], space = 100): Every lookup misses last_run_day, finishing in 4 consecutive days.
  • Identical category repeated ([5, 5, 5], space = 3): Lands on Days 1, 5, and 9 (1 + (k - 1) * (space + 1)).
  • Reset absorbed by intervening work ([2, 5, 8, 2], space = 2): Categories 5 and 8 occupy Days 2 and 3, allowing the second 2 on Day 4 without idling.
  • Massive space ([7, 7], space = 10**9): Jumps from Day 1 to Day 10**9 + 2 in one step without overflow thanks to Python's arbitrary-precision integers.

Common mistakes

  • Off-by-one in the unlock formula (+ space instead of + space + 1): Requiring space = 3 full intervening days after Day 1 blocks Days 2, 3, and 4, so Day 5 (1 + 3 + 1) is the earliest repeat day. Using + space unlocks a day early and returns 8 instead of 10 on Example 1.
  • Advancing one idle day per loop iteration: Incrementing current_day += 1 inside a while loop degrades to O(n * space) and times out when space is 10**9.
  • Recording list indices instead of calendar days: As soon as one idle jump occurs, i and current_day diverge; reset gaps measure calendar days, not queue positions.
  • Permuting items to fill idle slots: Unlike unordered CPU task-cooldown puzzles, products here must execute strictly in input order.

Follow-up questions

  • How does the minimum day count change if you are permitted to rearrange the sequence of items in any order? Once reordering is legal, only the highest-frequency category limits the schedule. If the maximum count of any single category is max_freq and ties categories share that maximum count, arranging max_freq - 1 blocks of length space + 1 followed by a final row of ties items yields max(len(products), (max_freq - 1) * (space + 1) + ties) in O(n) time via collections.Counter.
  • What would you store and return if the caller needed the exact day number assigned to each item without blowing up memory when space is huge? Append current_day to a sparse list assigned_days of length n on each iteration so assigned_days[i] gives the exact day products[i] runs in O(n) space. Never materialize a day-by-day calendar array padded with None for idle days, because a single space = 10**9 jump would allocate a billion entries and exhaust RAM.
  • If items arrive as an unbounded stream with millions of distinct IDs while space is a small constant like 50, how can you cap memory usage? Any category whose last run was on or before current_day - space is already unlocked and no longer constrains future items. Keep a FIFO queue (collections.deque, a first-in, first-out double-ended queue supporting O(1) front pops and back appends) of (day, category) pairs; before scheduling each new item, pop front entries satisfying day + space + 1 <= current_day + 1 and remove last_run_day[category] whenever its stored day equals day. Because at most one item runs per day, at most space + 1 entries remain active at once, bounding memory to O(min(u, space + 1)) while preserving O(n) runtime.

Follow-up questions

Similar questions

More Interactive Brokers interview questions

All 3 Interactive Brokers questions →