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 beforeproducts[i + 1]. - At most one item may finish on any single day.
- Once category
cfinishes on dayd, at leastspacecomplete intervening days must pass before another item of categoryccan run—making dayd + space + 1the earliest legal repeat day for categoryc. - While category
cis 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
4ran on Day 1 and requires3full intervening days, unlocking on Day1 + 3 + 1 = 5) - Day 5: category
4 - Day 6: category
9 - Day 7: category
7(unlocked on Day2 + 3 + 1 = 6, so no extra wait is needed) - Days 8–9: idle (category
9ran on Day 6 and unlocks on Day6 + 3 + 1 = 10) - Day 10: category
9
- Day 1: category
Example 2
- Input:
products = [2, 5, 8, 2],space = 2 - Output:
4 - Explanation: Categories
2,5, and8run 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 second2runs immediately on Day 4 with zero idle days.
Constraints
0 <= len(products) <= 10^5-10^9 <= products[i] <= 10^90 <= space <= 10^9
Step-by-step walkthrough
Understand the calendar rules and reset gap
We process
productsstrictly in index order, completing at most one item per day starting on Day1(returning0whenproductsis empty). Whenever categorycruns on Dayd,spacecomplete intervening days must separate it from the next copy of categoryc: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 5During those intervening days (Days
2,3, and4above), the line can run the next item inproductsif its own category is unlocked; otherwise the line sits idle.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
spaceis tiny, yetspacecan reach10^9. Onproducts = [7, 7]withspace = 1_000_000_000:- Day
1: run7. - Days
2through1_000_000_001: burn a billion idle loop iterations! - Day
1_000_000_002: run the second7.
Instead of stepping across idle days in
O(n * space)time, we can compute the exact unlock day and jump directly there inO(1).- Day
Greedy choice: run every item as early as legal
Suppose all items before index
iare scheduled and itemi - 1landed oncurrent_day. What bounds the daydof the currentcategory?- Sequential capacity: Only one item finishes per day, requiring
d >= current_day + 1. - Category reset: If
categoryappeared earlier, only its most recent daylast_run_day[category]restricts us (any older occurrence unlocked even earlier), requiringd >= 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 raisescurrent_day + 1andlast_run_day[category] + space + 1, which can never let any subsequent item run sooner.- Sequential capacity: Only one item finishes per day, requiring
Store each category's latest day in a dictionary
Keep a dictionary
last_run_daymapping each seencategoryto its latest 1-based calendar day, alongsidecurrent_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_dayWhen
productsis empty, the loop never executes andcurrent_dayremains0.Trace Example 1 step by step
Let's trace
products = [4, 7, 4, 9, 7, 9]withspace = 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: 10Complete 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 thenitems once, performing oneO(1)average-time dictionary lookup, constant-time integer arithmetic, and oneO(1)dictionary update per item, completely independent ofspace. - Space:
O(u).last_run_dayholds at most one entry per distinct category (O(u) <= O(n)).
Edge cases
- Empty
products([]):current_daystarts at0and the loop skips directly toreturn 0. - Zero reset gap (
space = 0):last_run_day[category] + 0 + 1 <= current_day + 1, so zero idle days occur and the answer equalslen(products). - All unique categories (
[1, 2, 3, 4],space = 100): Every lookup misseslast_run_day, finishing in4consecutive days. - Identical category repeated (
[5, 5, 5],space = 3): Lands on Days1,5, and9(1 + (k - 1) * (space + 1)). - Reset absorbed by intervening work (
[2, 5, 8, 2],space = 2): Categories5and8occupy Days2and3, allowing the second2on Day4without idling. - Massive
space([7, 7],space = 10**9): Jumps from Day1to Day10**9 + 2in one step without overflow thanks to Python's arbitrary-precision integers.
Common mistakes
- Off-by-one in the unlock formula (
+ spaceinstead of+ space + 1): Requiringspace = 3full intervening days after Day1blocks Days2,3, and4, so Day5(1 + 3 + 1) is the earliest repeat day. Using+ spaceunlocks a day early and returns8instead of10on Example 1. - Advancing one idle day per loop iteration: Incrementing
current_day += 1inside awhileloop degrades toO(n * space)and times out whenspaceis10**9. - Recording list indices instead of calendar days: As soon as one idle jump occurs,
iandcurrent_daydiverge; reset gaps measure calendar days, not queue positions. - Permuting items to fill idle slots: Unlike unordered CPU task-cooldown puzzles,
productshere 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_freqandtiescategories share that maximum count, arrangingmax_freq - 1blocks of lengthspace + 1followed by a final row oftiesitems yieldsmax(len(products), (max_freq - 1) * (space + 1) + ties)inO(n)time viacollections.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_dayto a sparse listassigned_daysof lengthnon each iteration soassigned_days[i]gives the exact dayproducts[i]runs inO(n)space. Never materialize a day-by-day calendar array padded withNonefor idle days, because a singlespace = 10**9jump 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 - spaceis already unlocked and no longer constrains future items. Keep a FIFO queue (collections.deque, a first-in, first-out double-ended queue supportingO(1)front pops and back appends) of(day, category)pairs; before scheduling each new item, pop front entries satisfyingday + space + 1 <= current_day + 1and removelast_run_day[category]whenever its stored day equalsday. Because at most one item runs per day, at mostspace + 1entries remain active at once, bounding memory toO(min(u, space + 1))while preservingO(n)runtime.
Follow-up questions
- How does the minimum day count change if you are permitted to rearrange the sequence of items in any order?
- 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?
- 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?
Similar questions
- Marginal Tax Across Income Tiers
- Progressive Marginal Tax Calculator
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance