Topological Sort

Count in-degrees of each node and build graph. Run Topological sort. Count the number of courses completed equals total number of courses.

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        Map<Integer, Set<Integer>> map = new HashMap<>();
        int[] indegree = new int[numCourses];
        for (int[] pre : prerequisites) {
            int from = pre[1], to = pre[0];
            map.putIfAbsent(from, new HashSet<>());
            map.get(from).add(to);
            indegree[to]++;
        }  
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < indegree.length; i++) {
            if (indegree[i] == 0) {
                q.offer(i);
            }
        }
        while (!q.isEmpty()) {
            int curt = q.poll();
            numCourses--;
            for (int next : map.getOrDefault(curt, new HashSet<>())) {
                if (--indegree[next] == 0) {
                    q.offer(next);
                }
            }
        }
        return numCourses == 0;
    }

Add visited courses to the list. Check if list size == numCourses before return.

1136. Parallel Courses

1. Given a dependency where for java packages p1,p2,p3

  • p1:{p2,p3}

    p2:{p3}

    p3:{}

  • This means p1 can be compiled when compilation of p2 and p3 done

  • p2 can compile when p3 is compiled

  • p3 can start as it does not have any dependence.

Write a function to calculate build order given a project with a list of dependencies that also need to be built.

Build the graph. Store indegrees in a different map. Check if all chars are in the array by using return sb.length() == indegree.size() ? sb.toString() : "";

Topological sort with lots of validations. Construct graph from provided sequences. Be care of when a sequence may exist multiple times, and there might be sequence with 1 size.

While traversing, check if the queue size > 1, this means there are multiple path. Also check if curt match with org[index++] and index is not out of bound.

As completed, check if traveled all nodes in org and graph.

Given a 2D array of distinct integers with n numbers, "compress" the array such that the resulting array's numbers are in the range [1, n] and their relative order is kept.

Relative order means that if a number at position (row1, col1) is smaller than a number at position (row2, col2) in the original array, it should still have that relationship in the resulting array.

Sort and reverse map the position and values.

Follow-up:

Compress the array to make the numbers as small as possible as long as the relative order holds true for numbers in the same row and column.

Build DAG and count indegree. Use Topological sort with Level order traversal to assign values.

Last updated

Was this helpful?