LeetCode #3604 — MEDIUM

Minimum Time to Reach Destination in Directed Graph

Move from brute-force thinking to an efficient approach using core interview patterns strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer n and a directed graph with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [ui, vi, starti, endi] indicates an edge from node ui to vi that can only be used at any integer time t such that starti <= t <= endi.

You start at node 0 at time 0.

In one unit of time, you can either:

  • Wait at your current node without moving, or
  • Travel along an outgoing edge from your current node if the current time t satisfies starti <= t <= endi.

Return the minimum time required to reach node n - 1. If it is impossible, return -1.

Example 1:

Input: n = 3, edges = [[0,1,0,1],[1,2,2,5]]

Output: 3

Explanation:

The optimal path is:

  • At time t = 0, take the edge (0 → 1) which is available from 0 to 1. You arrive at node 1 at time t = 1, then wait until t = 2.
  • At time t = 2, take the edge (1 → 2) which is available from 2 to 5. You arrive at node 2 at time 3.

Hence, the minimum time to reach node 2 is 3.

Example 2:

Input: n = 4, edges = [[0,1,0,3],[1,3,7,8],[0,2,1,5],[2,3,4,7]]

Output: 5

Explanation:

The optimal path is:

  • Wait at node 0 until time t = 1, then take the edge (0 → 2) which is available from 1 to 5. You arrive at node 2 at t = 2.
  • Wait at node 2 until time t = 4, then take the edge (2 → 3) which is available from 4 to 7. You arrive at node 3 at t = 5.

Hence, the minimum time to reach node 3 is 5.

Example 3:

Input: n = 3, edges = [[1,0,1,3],[1,2,3,5]]

Output: -1

Explanation:

  • Since there is no outgoing edge from node 0, it is impossible to reach node 2. Hence, the output is -1.

Constraints:

  • 1 <= n <= 105
  • 0 <= edges.length <= 105
  • edges[i] == [ui, vi, starti, endi]
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 0 <= starti <= endi <= 109

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer n and a directed graph with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [ui, vi, starti, endi] indicates an edge from node ui to vi that can only be used at any integer time t such that starti <= t <= endi. You start at node 0 at time 0. In one unit of time, you can either: Wait at your current node without moving, or Travel along an outgoing edge from your current node if the current time t satisfies starti <= t <= endi. Return the minimum time required to reach node n - 1. If it is impossible, return -1.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: General problem-solving

Example 1

3
[[0,1,0,1],[1,2,2,5]]

Example 2

4
[[0,1,0,3],[1,3,7,8],[0,2,1,5],[2,3,4,7]]

Example 3

3
[[1,0,1,3],[1,2,3,5]]
Step 02

Core Insight

What unlocks the optimal approach

  • Use the <code>Dijkstra</code> algorithm over states (node, time).
  • At node <code>u</code> with current time <code>t</code>, you can only use an edge <code>[u, v, start, end]</code> if <code>t <= end</code>.
  • If <code>t < start</code>, wait until <code>start</code>, then traverse (arriving at <code>start + 1</code>).
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3604: Minimum Time to Reach Destination in Directed Graph
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3604: Minimum Time to Reach Destination in Directed Graph
// package main
// 
// import (
// 	"container/heap"
// 	"math"
// )
// 
// // https://space.bilibili.com/206214
// func minTime(n int, edges [][]int) int {
// 	type edge struct{ to, start, end int }
// 	g := make([][]edge, n)
// 	for _, e := range edges {
// 		x, y := e[0], e[1]
// 		g[x] = append(g[x], edge{y, e[2], e[3]})
// 	}
// 
// 	dis := make([]int, n)
// 	for i := range dis {
// 		dis[i] = math.MaxInt
// 	}
// 	dis[0] = 0
// 	h := hp{{}}
// 	for len(h) > 0 {
// 		p := heap.Pop(&h).(pair)
// 		d := p.d
// 		x := p.x
// 		if d > dis[x] {
// 			continue
// 		}
// 		if x == n-1 {
// 			return d
// 		}
// 		for _, e := range g[x] {
// 			y := e.to
// 			newD := max(d, e.start) + 1
// 			if newD-1 <= e.end && newD < dis[y] {
// 				dis[y] = newD
// 				heap.Push(&h, pair{newD, y})
// 			}
// 		}
// 	}
// 	return -1
// }
// 
// type pair struct{ d, x int }
// type hp []pair
// func (h hp) Len() int           { return len(h) }
// func (h hp) Less(i, j int) bool { return h[i].d < h[j].d }
// func (h hp) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
// func (h *hp) Push(v any)        { *h = append(*h, v.(pair)) }
// func (h *hp) Pop() (v any)      { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.

OPTIMIZED
O(n) time
O(1) space

Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.

Shortcut: If you are using nested loops on an array, there is almost always an O(n) solution. Look for the right auxiliary state.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.