Similar Problems

Similar Problems not available

Single Threaded Cpu - Leetcode Solution


  • google

LeetCode:  Single Threaded Cpu Leetcode Solution

Difficulty: Medium

Topics: sorting heap-priority-queue array  

Problem Description:

You are given a CPU that can execute some tasks. Each task will be represented by a positive integer and you have to run the tasks in order. You cannot execute two tasks simultaneously.

Given a non-empty array of positive integers representing the task queue, find the minimum time required to execute all the tasks.


Input: [1,2,3,4,5], n = 2 Output: 9 Explanation: The CPU executes the tasks in the following order:

  • Cycle 1: Task 1
  • Cycle 2: Task 2
  • Cycle 3: Task 3
  • Cycle 4: Task 4
  • Cycle 5: Task 5
  • Cycle 6: Idle
  • Cycle 7: Idle
  • Cycle 8: Idle
  • Cycle 9: Idle


The intuition to solve this problem is to simulate the execution of tasks on the CPU and calculate how much time it would take. We can do this by keeping track of the time it takes to execute a task and determine when the CPU is idle.

One solution is to use a priority queue to keep track of the tasks. We can use a map to count the frequencies of each task and then add the tasks to the priority queue in decreasing order based on the frequency.

We can then start executing the tasks one by one. For each task, we add it to a list of completed tasks and increment the time it takes to execute the task. If the size of the completed task list is less than the total number of tasks, we check if the CPU is idle. If it is, we increment the time by 1.

If the CPU is not idle, we check if the task queue is empty. If it is not, we add the next task to the priority queue based on its frequency. If the CPU is idle and the task queue is empty, we have completed all the tasks and return the total time it took.

Here is the Python code for the solution:

class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: freq_map = {} for task in tasks: freq_map[task] = freq_map.get(task, 0) + 1

    pq = [-freq_map[task] for task in freq_map]
    time = 0
    completed_tasks = []
    while pq or completed_tasks:
        if pq:
            task = heappop(pq)
            task += 1
            if task != 0:
        if len(completed_tasks) > n:
            task = completed_tasks.pop(0)
            if task is not None:
                heappush(pq, task)
        time += 1
    return time

Time Complexity: O(Nlog(N)), where N is the total number of tasks. Sorting the frequency map using a heap takes O(Nlog(N)) time. We then iterate through all the tasks and the time it takes is proportional to the total number of tasks.

Space Complexity: O(N), where N is the total number of tasks. We use a frequency map to count the frequencies of each task, which takes O(N) space. We also use a priority queue to keep track of the tasks, which takes O(N) space in the worst case.

Single Threaded Cpu Solution Code