<jupyter_start><jupyter_text>https://leetcode.com/problems/course-schedule/<jupyter_code># my solution
def canFinish(numCourses: int, prerequisites):
    adj = [set() for _ in range(numCourses)] # create adjacency matrix for each 
    adj_a = [set() for _ in range(numCourses)]
    for c,p in prerequisites:
        adj[c].add(p)
        adj_a[p].add(c)
    leaves = [v for v in range(numCourses) if len(adj[v]) == 0]
    while numCourses > 0:
        print(leaves)
        numCourses -= len(leaves)
        new_leaves = []
        for leaf in leaves:
            for i,c in enumerate(adj):
                if leaf in c: 
                    c.remove(leaf)
                    if len(c) == 0:
                        new_leaves.append(i)
        leaves = new_leaves
        if len(leaves) == 0 and numCourses > 0: return False
    return True
# my solution
def canFinish(numCourses: int, prerequisites):
    c_p = [set() for _ in range(numCourses)] # create matrix for each 
    p_c = [set() for _ in range(numCourses)]
    for c,p in prerequisites:
        c_p[c].add(p)
        p_c[p].add(c)
    leaves = [v for v in range(numCourses) if len(c_p[v]) == 0]
    while numCourses > 0:
        numCourses -= len(leaves)
        new_leaves = []
        for leaf in leaves: # remove leaves from c_p
            for c in p_c[leaf]:
                c_p[c].remove(leaf) # remove the req from all classes which require it
                if len(c_p[c]) == 0: # if the length of the class is now 0, it is now a new leaf
                    new_leaves.append(c)
        leaves = new_leaves
        if len(leaves) == 0 and numCourses > 0: return False
    return True
canFinish(2,[[0,1]])
canFinish(3,[[1,0],[2,0]])<jupyter_output>0 1
1 2
StarcoderdataJupyterStructuredCleanDedup