703952. Completing tasks

Easy

Completing Tasks

Slug: completing-tasks0454 Difficulty: Easy Id: 703952 Topic Tags: Arrays, Hash, Data Structures Company Tags: None

Summary

Given a list of tasks with their priorities and deadlines, your task is to complete the tasks in the correct order. The priority of each task is its deadline (the earlier the better). You have to sort the tasks based on their deadlines and then start executing them from the earliest deadline.

Detailed Explanation

The problem involves sorting an array of tasks based on their deadlines and then executing them in that order. We can use a simple sorting algorithm like Bubble Sort or Selection Sort to achieve this.

Here's a step-by-step breakdown of the solution:

  1. First, we create an empty list tasks to store the tasks.
  2. Then, for each task in the given array, we add it to our new list along with its deadline.
  3. Next, we sort the tasks list based on the deadlines.
  4. Finally, we iterate through the sorted tasks list and execute each task as they arrive.

Here's a diagram illustrating the steps:

          +---------------+
          |  Task 1      |
          +---------------+
                  |
                  v
+---------------+       +---------------+
| Deadline: 3    |       | Deadline: 2   |
+---------------+       +---------------+
                  |
                  v
+---------------+       +---------------+
| Task 2        |       | Task 3        |
+---------------+       +---------------+

Time Complexity: O(n log n) due to the sorting step, where n is the number of tasks. Space Complexity: O(n) for storing the tasks and deadlines.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Arrays;
import java.util.List;

public class TaskExecutor {
    public static void executeTasks(List<Task> tasks) {
        // Sort tasks based on their deadlines
        tasks.sort((t1, t2) -> Integer.compare(t2.getDeadline(), t1.getDeadline()));
        
        // Execute tasks in the sorted order
        for (Task task : tasks) {
            System.out.println("Executing task: " + task.getName());
        }
    }

    public static class Task {
        private String name;
        private int deadline;

        public Task(String name, int deadline) {
            this.name = name;
            this.deadline = deadline;
        }

        public int getDeadline() {
            return deadline;
        }

        public String getName() {
            return name;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.