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.
Move from brute-force thinking to an efficient approach using topological sort strategy.
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
[0, 1], indicates that to take course 0 you have to first take course 1.Return true if you can finish all courses. Otherwise, return false.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCoursesProblem summary: There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Topological Sort
2 [[1,0]]
2 [[1,0],[0,1]]
course-schedule-ii)graph-valid-tree)minimum-height-trees)course-schedule-iii)build-a-matrix-with-conditions)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #207: Course Schedule
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] g = new List[numCourses];
Arrays.setAll(g, k -> new ArrayList<>());
int[] indeg = new int[numCourses];
for (var p : prerequisites) {
int a = p[0], b = p[1];
g[b].add(a);
++indeg[a];
}
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < numCourses; ++i) {
if (indeg[i] == 0) {
q.offer(i);
}
}
while (!q.isEmpty()) {
int i = q.poll();
--numCourses;
for (int j : g[i]) {
if (--indeg[j] == 0) {
q.offer(j);
}
}
}
return numCourses == 0;
}
}
// Accepted solution for LeetCode #207: Course Schedule
func canFinish(numCourses int, prerequisites [][]int) bool {
g := make([][]int, numCourses)
indeg := make([]int, numCourses)
for _, p := range prerequisites {
a, b := p[0], p[1]
g[b] = append(g[b], a)
indeg[a]++
}
q := []int{}
for i, x := range indeg {
if x == 0 {
q = append(q, i)
}
}
for len(q) > 0 {
i := q[0]
q = q[1:]
numCourses--
for _, j := range g[i] {
indeg[j]--
if indeg[j] == 0 {
q = append(q, j)
}
}
}
return numCourses == 0
}
# Accepted solution for LeetCode #207: Course Schedule
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
g = [[] for _ in range(numCourses)]
indeg = [0] * numCourses
for a, b in prerequisites:
g[b].append(a)
indeg[a] += 1
q = [i for i, x in enumerate(indeg) if x == 0]
for i in q:
numCourses -= 1
for j in g[i]:
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return numCourses == 0
// Accepted solution for LeetCode #207: Course Schedule
use std::collections::VecDeque;
impl Solution {
pub fn can_finish(mut num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool {
let mut g: Vec<Vec<i32>> = vec![vec![]; num_courses as usize];
let mut indeg: Vec<i32> = vec![0; num_courses as usize];
for p in prerequisites {
let a = p[0] as usize;
let b = p[1] as usize;
g[b].push(a as i32);
indeg[a] += 1;
}
let mut q: VecDeque<usize> = VecDeque::new();
for i in 0..num_courses {
if indeg[i as usize] == 0 {
q.push_back(i as usize);
}
}
while let Some(i) = q.pop_front() {
num_courses -= 1;
for &j in &g[i] {
let j = j as usize;
indeg[j] -= 1;
if indeg[j] == 0 {
q.push_back(j);
}
}
}
num_courses == 0
}
}
// Accepted solution for LeetCode #207: Course Schedule
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
const g: number[][] = Array.from({ length: numCourses }, () => []);
const indeg: number[] = Array(numCourses).fill(0);
for (const [a, b] of prerequisites) {
g[b].push(a);
indeg[a]++;
}
const q: number[] = [];
for (let i = 0; i < numCourses; ++i) {
if (indeg[i] === 0) {
q.push(i);
}
}
for (const i of q) {
--numCourses;
for (const j of g[i]) {
if (--indeg[j] === 0) {
q.push(j);
}
}
}
return numCourses === 0;
}
Use this to step through a reusable interview workflow for this problem.
Repeatedly find a vertex with no incoming edges, remove it and its outgoing edges, and repeat. Finding the zero-in-degree vertex scans all V vertices, and we do this V times. Removing edges touches E edges total. Without an in-degree array, this gives O(V × E).
Build an adjacency list (O(V + E)), then either do Kahn's BFS (process each vertex once + each edge once) or DFS (visit each vertex once + each edge once). Both are O(V + E). Space includes the adjacency list (O(V + E)) plus the in-degree array or visited set (O(V)).
Review these before coding to avoid predictable interview regressions.
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.