DAG Schedule Analysis and Windowed Checkpoint DP
Dynamic ProgrammingModel answerLast updated
Compute critical-path latency and peak concurrency for a task DAG, then find minimum-cost checkpoint placement under a sliding-window coverage constraint.
Background
Execution engines for data pipelines need two things to run efficiently: a way to schedule interdependent tasks as tightly as possible, and a strategy for placing recovery checkpoints without spending more than necessary. You will implement both as methods on a single class.
class PipelineOptimizer:
def analyze_dag(
self, n: int, edges: list[list[int]], durations: list[int]
) -> list[int]:
pass
def min_checkpoint_cost(self, costs: list[int], max_window: int) -> int:
pass
Part 1: Schedule a Task Graph
You are given n tasks numbered 0 through n - 1. Each task has an integer execution time given by durations[i]. The list edges contains pairs [u, v] meaning task u must finish before task v can start.
Scheduling rules:
- Every task starts at the earliest non-negative time when all of its prerequisites are done.
- There is no cap on how many tasks may run at once.
- A task running during
[start, end)occupies that half-open interval. If one task ends at timetand another starts at timet, they are not considered to overlap.
Return [min_latency, max_parallelism]:
min_latency— the time at which the last task finishes.max_parallelism— the largest number of tasks executing simultaneously at any single moment.
Example
optimizer = PipelineOptimizer()
optimizer.analyze_dag(
n=4,
edges=[[0,1],[0,2],[1,3],[2,3]],
durations=[3, 2, 4, 1]
)
# Returns: [8, 2]
Task 0 runs [0, 3). Tasks 1 and 2 both become ready at time 3 and run concurrently: task 1 during [3, 5) and task 2 during [3, 7). Their overlap [3, 5) gives peak parallelism 2. Task 3 waits for both and runs [7, 8). Total latency is 8.
Part 2: Cheapest Checkpoint Coverage
A pipeline processes a sequence of m operations. Each operation i has a cost costs[i] to place a checkpoint there.
A checkpoint placement is valid when every contiguous block of max_window consecutive operations contains at least one checkpoint — formally, for every k with 0 <= k <= m - max_window, at least one index in [k, k + max_window) must be chosen.
Return the minimum total cost of a valid placement.
Example
optimizer = PipelineOptimizer()
optimizer.min_checkpoint_cost(
costs=[3, 2, 4, 1, 5, 2],
max_window=3
)
# Returns: 3
Placing checkpoints at index 1 (cost 2) and index 3 (cost 1) covers every window of size 3. Total cost is 3.
Constraints
1 <= n <= 2 × 10⁴0 <= len(edges) <= 5 × 10⁴; the graph is a valid DAG (no cycles).1 <= durations[i] <= 10⁶1 <= m == len(costs) <= 10⁵1 <= max_window <= m1 <= costs[i] <= 10⁹
What is expected
For each part, explain your approach, argue correctness for the tricky boundary cases (the tie-breaking rule in Part 1; the first and last window positions in Part 2), state time and space complexity, and provide clean working code.
Hints
Hint 1
For Part 1, process nodes in topological order so every predecessor's finish time is locked in before you compute a successor's start time. Then model each task as a half-open interval and think carefully about how to sort end and start events that fall on the same timestamp.
Hint 2
For Part 2, reframe the window constraint as a recurrence: if the most recent checkpoint before position i was at position j, then i - j must be less than max_window or the gap is uncovered. That turns the problem into a 1-D DP where each transition looks back over a fixed-width range of previous states.
Hint 3
The sliding-window minimum over a range of fixed width that advances one step at a time can be maintained in O(1) amortized per step with a monotonic deque. Think about which end of the deque to evict from for out-of-range indices versus dominated values.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: DAG Schedule Analysis
Approach
With no resource constraints, every task starts at the earliest moment all its predecessors have finished:
start[v] = max(end[u] for u in predecessors(v)), or 0 if v has no predecessors
end[v] = start[v] + durations[v]
Processing nodes in topological order (Kahn's BFS algorithm) guarantees that when you process v, every end[u] you need is already final. This is just longest-path propagation on the DAG.
Latency is max(end) across all nodes — the critical path.
Parallelism requires knowing how many tasks overlap at each moment. Model each task as the half-open interval [start[i], end[i]) and build a timeline of events. The key boundary rule is that a task ending at time t and another starting at time t do not overlap. This means end events must be processed before start events at the same timestamp. Representing a start as delta +1 and an end as delta -1 and sorting by (time, delta) achieves this automatically, because -1 < +1. A running prefix sum over the sorted events then gives the instantaneous count; track its maximum.
Correctness details
- Topological order: Kahn's algorithm initializes a queue with all zero-in-degree nodes and relaxes each edge once, so every predecessor is finalized before any successor.
- Tie-breaking: Without the sort trick, you could incorrectly count a task as simultaneously running with its immediate successor. The
(time, delta)tuple sort is a clean way to enforce the half-open-interval semantics without any special-case code. - Disconnected components: All source nodes (in-degree 0) start at time 0 and are counted together in the sweep, which is correct — they genuinely run concurrently.
Complexity
- O(n + E) for Kahn's and start/end propagation.
- O(n log n) for sorting 2n events.
- O(n + E) space.
Part 2: Sliding-Window Checkpoint DP
Reframing the constraint
Let w = max_window. A placement is valid when there is no gap of w or more consecutive uncheckpointed operations. Equivalently, if the last checkpoint placed before index i was at index j, then i - j < w — otherwise the window [j+1, j+w) would be uncovered.
This gives a DP: let dp[i] be the minimum cost to cover all windows entirely within [0, i], with the last checkpoint exactly at i.
-
Base case: For
i < w, placing a checkpoint atiwith no predecessor is always valid for all windows that end at or beforei. Sodp[i] = costs[i]. -
Transition: For
i >= w, the previous checkpoint must lie in[i-w+1, i-1](any earlier and the gap exceedsw-1):dp[i] = costs[i] + min(dp[i-w+1 .. i-1]) -
Answer: The final checkpoint must be late enough to cover the last window
[m-w, m-1], so it must be at some index in[m-w, m-1]:answer = min(dp[m-w .. m-1])
Sliding-window minimum with a monotonic deque
The transition looks back over a window of fixed width w-1 that slides one step at a time — a classic application for a monotonic deque. The deque stores indices in increasing order and maintains the invariant that dp values are non-decreasing from front to back:
- Before computing
dp[i], pop from the front any index that has fallen out of the range[i-w+1, i-1]. - The front of the deque now holds the index with the minimum
dpvalue in the valid range. - After computing
dp[i], pop from the back any index whosedpvalue is>= dp[i](they are dominated), then appendi.
Each index enters and leaves the deque at most once, giving O(m) total.
Verifying on the example
costs = [3, 2, 4, 1, 5, 2], w = 3:
| i | dp[i] | Reasoning |
|---|---|---|
| 0 | 3 | base case |
| 1 | 2 | base case |
| 2 | 4 | base case |
| 3 | 1 + min(dp[1], dp[2]) = 1 + 2 = 3 | transition, range [1,2] |
| 4 | 5 + min(dp[2], dp[3]) = 5 + 3 = 8 | transition, range [2,3] — wait, deque front is index 1 still in range [2,3]? No: i=4, range is [i-w+1, i-1] = [2,3]. dp[2]=4, dp[3]=3, min=3. dp[4]=8. |
| 5 | 2 + min(dp[3], dp[4]) = 2 + 3 = 5 | transition, range [3,4] |
Answer: min(dp[3], dp[4], dp[5]) = min(3, 8, 5) = 3. Matches expected output.
Edge cases
max_window = 1: every index is required; answer issum(costs).max_window = m: one window covers everything; answer ismin(costs).- Costs up to 10⁹ and m up to 10⁵ means sums can reach ~10¹⁴. Python handles this natively; in Java/C++ use
long.
Complexity
- O(m) time, O(m) space. The space can be reduced to O(w) by keeping only the dp values referenced by the active deque window.
Full Implementation
from collections import deque
class PipelineOptimizer:
def analyze_dag(
self, n: int, edges: list[list[int]], durations: list[int]
) -> list[int]:
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
# Propagate earliest start times in topological order
start = [0] * n
end = [0] * n
q = deque(i for i in range(n) if indeg[i] == 0)
while q:
u = q.popleft()
end[u] = start[u] + durations[u]
for v in adj[u]:
if end[u] > start[v]:
start[v] = end[u]
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
min_latency = max(end)
# Build events; sort (time, delta) so -1 (end) beats +1 (start) at ties
events = []
for i in range(n):
events.append((start[i], 1))
events.append((end[i], -1))
events.sort()
running = peak = 0
for _, delta in events:
running += delta
if running > peak:
peak = running
return [min_latency, peak]
def min_checkpoint_cost(self, costs: list[int], max_window: int) -> int:
m, w = len(costs), max_window
dp = [0] * m
dq: deque[int] = deque() # indices; dp values increase front → back
for i in range(m):
if i >= w:
# Evict indices that are now out of the valid predecessor range
while dq and dq[0] < i - w + 1:
dq.popleft()
dp[i] = costs[i] + dp[dq[0]]
else:
# Base case: first checkpoint with no required predecessor
dp[i] = costs[i]
# Maintain monotone deque: remove dominated back entries
while dq and dp[dq[-1]] >= dp[i]:
dq.pop()
dq.append(i)
return min(dp[m - w:])
Common Mistakes
- Part 1 tie-breaking: Sorting only by time and processing starts before ends inflates the parallelism count for chains where tasks touch end-to-start.
- Part 2 window boundary: Off-by-one errors when defining the base case range or the final answer range. The last window is
[m-w, m-1], so the final checkpoint must land in that exact span. - Part 2 deque eviction order: Always evict out-of-range indices from the front before reading
dq[0]for the transition, or you may use a stale minimum.