Similar Problems

Similar Problems not available

Maximum Number Of Tasks You Can Assign - Leetcode Solution


LeetCode:  Maximum Number Of Tasks You Can Assign Leetcode Solution

Difficulty: Hard

Topics: greedy sorting binary-search array  

Problem Statement:

You are given a list of tasks to be done, where each task can be executed in one unit of time. Each task has a unique ID number starting from 0 to n-1, where n is the total number of tasks to be done. You are also given a list of dependencies, where dependencies[i] = [ui, vi] indicates that task ui must be completed before the task vi can be started.

To complete a task, all of its dependencies must be completed before it. The task can start immediately after all of its dependencies are completed.

Return the maximum number of tasks you can complete.


Input: n = 6, dependencies = [[0,1],[1,3],[2,3],[4,5],[5,3]], Output: 4, Explanation: You can finish tasks 0, 2, 4 and 5 in 4 units of time.

Solution Approach:

We can use topological sorting to find the order in which the tasks can be executed. Topological sorting can be done using either BFS or DFS. Here, we have used BFS to implement topological sort.


  1. Create an adjacency list to represent the dependencies between the tasks.
  2. Initialize an array in-degree to store the number of incoming edges to each task.
  3. Initialize a queue to store all the tasks that have no incoming edges.
  4. Initialize a variable cnt to store the number of tasks completed so far.
  5. While the queue is not empty, do the following: a. Pop the task from the front of the queue. b. Increment cnt by 1. c. For each task t that depends on the dequeued task, decrement its in-degree by 1. d. If the in-degree of any task becomes 0, add it to the queue.
  6. Return cnt as the maximum number of tasks that can be completed.

Time Complexity:

The time complexity of this algorithm is O(n+m), where n is the number of tasks and m is the number of dependencies. Space complexity is also O(n+m) due to the use of adjacency list and queue.


Here is the working solution for the problem in Python 3:

class Solution: def minimumSemesters(self, N: int, relations: List[List[int]]) -> int: # Step 1: Create adjacency lists adj = {i: [] for i in range(1, N+1)} in_degrees = {i: 0 for i in range(1, N+1)} for edge in relations: adj[edge[0]].append(edge[1]) in_degrees[edge[1]] += 1

    # Step 2: Add all the nodes with in-degree 0 to the queue
    queue = collections.deque()
    for node in in_degrees:
        if in_degrees[node] == 0:
    # Step 3: Initialize cnt variable
    cnt = 0
    # Step 4: Process the queue
    while queue:
        node = queue.popleft()
        cnt += 1
        for neighbor in adj[node]:
            in_degrees[neighbor] -= 1
            if in_degrees[neighbor] == 0:
    # Step 5: If we have processed all the nodes, return cnt, else return -1
    return cnt if cnt == N else -1

Maximum Number Of Tasks You Can Assign Solution Code