Leetcode #207 Course Schedule

Leetcode #207 Course Schedule

Difficulty: Medium

For this type of scheduling question, it can be solved using Topological Sort. It's basically Graph BFS problem.

Though process:

  • Initialize graph
  • Build the graph
  • Find the source node ( A node with no incoming edge)
  • Traverse the graph via BFS, using a stack - FIFO
  • If final output is same as total number of vertices, it can be schedule.

Time complexity: O(v+e) v for the vertices, e for it's edge

Link: Course Schedule

/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {boolean}
 */
var canFinish = function(numCourses, prerequisites) {
    let sortedOrder = [];

    // Init the graph
    let inDegree = Array(numCourses).fill(0);
    let graph = Array(numCourses).fill(0).map(() => Array());

    // Build the graph
    prerequisites.forEach((edge) =>{
    let parent = edge[0];
    let child = edge[1];

    graph[parent].push(child);
    inDegree[child]++;
    });

    // Find source
    let source = []
    for(let i =0; i<inDegree.length; i++){
        if(inDegree[i] == 0){
          source.push(i)
        }
    }

    // BFS traverse
    while(source.length >0){
        const vertex = source.shift();
        sortedOrder.push(vertex);

        graph[vertex].forEach((child) => {
          inDegree[child]--;
          if(inDegree[child] == 0){
            source.push(child)
          }
        })
    }

    return sortedOrder.length == numCourses;
};