class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { if(numCourses == 0) { return new int[0]; } Map> dependencies = new HashMap<>(); int[] connections = new int[numCourses]; for (int[] pair : prerequisites) { if (!dependencies.containsKey(pair[1])) { dependencies.put(pair[1], new ArrayList<>()); } dependencies.get(pair[1]).add(pair[0]); connections[pair[0]]++; } int[] result = new int[numCourses]; int runner = 0; Queue queue = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (connections[i] == 0) { queue.offer(i); } } while (!queue.isEmpty()) { int parent = queue.poll(); result[runner++] = parent; if (dependencies.containsKey(parent)) { for (int child : dependencies.get(parent)) { if (connections[child]-- == 1) { queue.offer(child); } } } } return runner == numCourses ? result : new int[0]; }}