← Deloitte bank

Deloitte · Question 57 · Graphs

Topological Sort / Course Schedule (II)

GraphsJavacode⏱ O(V+E)💾 O(V+E)
Service-based

Problem

Produce an ordering of courses given prerequisites using Kahn's BFS topological sort.

Approach

Emit zero-indegree courses; leftovers mean a cycle.

Time O(V+E)Space O(V+E)

How it works

  1. 1Build the graph and indegrees.
  2. 2Emit zero-indegree courses BFS-style.
  3. 3Full order means feasible; else empty.

Sample input / output

Input:
numCourses = 2, prerequisites = [[1, 0]]
Output:
[0, 1]

Constraints

1 <= numCourses <= 2000.

Solution — read it, then walk it

Time O(V+E)Space O(V+E)Loops 5Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]findOrder(int numCourses,int[][] pre)List<List<Integer>> g = newArrayList<>()for (int i = 0; i <numCourses; i++)g.add(ne…DEFINE [] indeg = newint[numCourses]for (int[] p : pre)g.get(p[1]).add(p[0])indeg[p[0]]++Queue<Integer> q = newArrayDeque<>()for (int i = 0; i <numCourses; i++)if (indeg[i] == 0)q.add(i)DEFINE [] res = newint[numCourses]DEFINE idx = 0while (!q.isEmpty())DEFINE u = q.poll()res[idx++] = ufor (int v : g.get(u))if (--indeg[v] == 0)q.add(v)RETURN idx == numCourses ?res : new int[0]DEFINE static voidmain(String[] args)System.out.println(Arrays.toString(findOrder(2,new int[][]{{1, 0}})))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits