Leetcode 1834: Single-Threaded CPU

grid47
grid47
Exploring patterns and algorithms
May 7, 2024 6 min read

You are given a list of tasks, where each task is represented by a pair of integers: [enqueueTime, processingTime]. The task can only be processed once its enqueueTime has passed. Your goal is to find the order in which tasks are processed by a single-threaded CPU that follows a specific processing strategy.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n representing the number of tasks and a 2D array of integers tasks where each element tasks[i] = [enqueueTime[i], processingTime[i]].
Example: tasks = [[1,2], [2,4], [3,2], [4,1]]
Constraints:
• 1 <= n <= 10^5
• 1 <= enqueueTime[i], processingTime[i] <= 10^9
Output: The output should be an array of integers representing the order in which the CPU processes the tasks.
Example: [0, 2, 3, 1]
Constraints:
Goal: The goal is to determine the order of task processing by the CPU based on the rules outlined.
Steps:
• Sort the tasks based on their enqueueTime to determine when each task is available.
• Use a priority queue to store tasks based on their processing time and index.
• At each time step, process the task with the shortest processing time, breaking ties with the smallest index.
• Update the time as tasks are processed and track the order of processing.
Goal: The constraints on the input values ensure that the problem is solvable within the given limits.
Steps:
• 1 <= n <= 10^5
• 1 <= enqueueTime[i], processingTime[i] <= 10^9
Assumptions:
• The CPU processes one task at a time, and no task is preempted once started.
Input: tasks = [[1,2], [2,4], [3,2], [4,1]]
Explanation: At time = 1, task 0 is available, and the CPU starts processing it. The CPU continues processing tasks in the order of their availability and processing times, resulting in the output [0, 2, 3, 1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus