AlgoMaster Logo

Single-Threaded CPU

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Basic Sorting and Iteration

Intuition:

The basic idea is to represent tasks with their indices so they can be sorted effectively by when they arrive. Once sorted, we iterate through them and maintain a current time to simulate how tasks would be processed. Whenever the CPU is idle and there are no available tasks to process at that time, the CPU should skip time to the next task.

Steps:

  1. Parse each task into a list that stores the processing time and original index.
  2. Sort the list of tasks based on enqueue time as the primary key and original index as a secondary key.
  3. Iterate through the list of tasks, and process each task based on current time, updating current time as tasks are processed sequentially.
  4. Use a list to track the order of processed tasks.

Code:

2. Optimized Priority Queue

Intuition:

Rather than iterating over tasks and moving time sequentially, leveraging a priority queue can optimize task processing based on the shortest processing time. This approach directly jumps to the next available task time by using a priority queue which also handles tasks with identical processing times by their original indices.

Steps:

  1. Store the tasks with their indices, similar to the previous approach.
  2. Sort the tasks based on enqueue times.
  3. Use a priority queue that sorts tasks first by processing time, and then by original index.
  4. Iterate over tasks, but using the priority queue to decide processing order.
  5. As before, track the order of processed tasks.

Code: