1834. Single-Threaded CPU LeetCode Solution

In this guide, you will get 1834. Single-Threaded CPU LeetCode Solution with the best time and space complexity. The solution to Single-Threaded CPU problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Single-Threaded CPU solution in C++
  4. Single-Threaded CPU solution in Java
  5. Single-Threaded CPU solution in Python
  6. Additional Resources
1834. Single-Threaded CPU LeetCode Solution image

Problem Statement of Single-Threaded CPU

You are given n​​​​​​ tasks labeled from 0 to n – 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:

If the CPU is idle and there are no available tasks to process, the CPU remains idle.
If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
Once a task is started, the CPU will process the entire task without stopping.
The CPU can finish a task then start a new one instantly.

Return the order in which the CPU will process the tasks.

Example 1:

Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
– At time = 1, task 0 is available to process. Available tasks = {0}.
– Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
– At time = 2, task 1 is available to process. Available tasks = {1}.
– At time = 3, task 2 is available to process. Available tasks = {1, 2}.
– Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
– At time = 4, task 3 is available to process. Available tasks = {1, 3}.
– At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
– At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
– At time = 10, the CPU finishes task 1 and becomes idle.

See also  2379. Minimum Recolors to Get K Consecutive Black Blocks LeetCode Solution

Example 2:

Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
– At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
– Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
– At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
– At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
– At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
– At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
– At time = 40, the CPU finishes task 1 and becomes idle.

Constraints:

tasks.length == n
1 <= n <= 105
1 <= enqueueTimei, processingTimei <= 109

Complexity Analysis

  • Time Complexity: O(\texttt{sort})
  • Space Complexity: O(n)

1834. Single-Threaded CPU LeetCode Solution in C++

class Solution {
 public:
  vector<int> getOrder(vector<vector<int>>& tasks) {
    const int n = tasks.size();

    // Add index information.
    for (int i = 0; i < tasks.size(); ++i)
      tasks[i].push_back(i);

    vector<int> ans;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;
    int i = 0;      // tasks' index
    long time = 0;  // the current time

    ranges::sort(tasks);
    while (i < n || !minHeap.empty()) {
      if (minHeap.empty())
        time = max(time, static_cast<long>(tasks[i][0]));
      while (i < n && time >= tasks[i][0]) {
        minHeap.emplace(tasks[i][1], tasks[i][2]);
        ++i;
      }
      const auto [procTime, index] = minHeap.top();
      minHeap.pop();
      time += procTime;
      ans.push_back(index);
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

1834. Single-Threaded CPU LeetCode Solution in Java

class T {
  public int procTime;
  public int index;
  public T(int procTime, int index) {
    this.procTime = procTime;
    this.index = index;
  }
}

class Solution {
  public int[] getOrder(int[][] tasks) {
    final int n = tasks.length;
    int[][] A = new int[n][3];

    for (int i = 0; i < n; ++i) {
      A[i][0] = tasks[i][0];
      A[i][1] = tasks[i][1];
      A[i][2] = i;
    }

    int[] ans = new int[n];
    int ansIndex = 0;
    Queue<T> minHeap = new PriorityQueue<>((a, b)
                                               -> a.procTime == b.procTime
                                                      ? Integer.compare(a.index, b.index)
                                                      : Integer.compare(a.procTime, b.procTime));
    int i = 0;     // tasks' index
    long time = 0; // the current time

    Arrays.sort(A, Comparator.comparing(a -> a[0]));

    while (i < n || !minHeap.isEmpty()) {
      if (minHeap.isEmpty())
        time = Math.max(time, (long) A[i][0]);
      while (i < n && time >= (long) A[i][0]) {
        minHeap.offer(new T(A[i][1], A[i][2]));
        ++i;
      }
      final int procTime = minHeap.peek().procTime;
      final int index = minHeap.poll().index;
      time += procTime;
      ans[ansIndex++] = index;
    }

    return ans;
  }
}
// code provided by PROGIEZ

1834. Single-Threaded CPU LeetCode Solution in Python

class Solution:
  def getOrder(self, tasks: list[list[int]]) -> list[int]:
    n = len(tasks)
    A = [[*task, i] for i, task in enumerate(tasks)]
    ans = []
    minHeap = []
    i = 0  # tasks' index
    time = 0  # the current time

    A.sort()

    while i < n or minHeap:
      if not minHeap:
        time = max(time, A[i][0])
      while i < n and time >= A[i][0]:
        heapq.heappush(minHeap, (A[i][1], A[i][2]))
        i += 1
      procTime, index = heapq.heappop(minHeap)
      time += procTime
      ans.append(index)

    return ans
# code by PROGIEZ

Additional Resources

See also  2716. Minimize String Length LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.