Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1136: Parallel Courses

In this guide, we solve Leetcode #1136 Parallel Courses in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Graph, Topological Sort

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: n = 3, relations = [[1,3],[2,3]] Output: 2 Explanation: The figure above represents the given graph. In the first semester, you can take courses 1 and 2. In the second semester, you can take course 3.

Python Solution

class Solution: def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: g = defaultdict(list) indeg = [0] * n for prev, nxt in relations: prev, nxt = prev - 1, nxt - 1 g[prev].append(nxt) indeg[nxt] += 1 q = deque(i for i, v in enumerate(indeg) if v == 0) ans = 0 while q: ans += 1 for _ in range(len(q)): i = q.popleft() n -= 1 for j in g[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return -1 if n else ans

Complexity

The time complexity is O(n+m)O(n + m)O(n+m), and the space complexity is O(n+m)O(n + m)O(n+m). The space complexity is O(n+m)O(n + m)O(n+m).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy