Single Threaded Cpu

Solution For Single Threaded Cpu

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
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.

Step by Step Implementation For Single Threaded Cpu

 * This is the solution for the leetcode problem "single-threaded-cpu".
 * The problem is as follows:
 * Given a program that is a sequence of instructions, each represented by a number,
 * and a CPU that can execute one instruction at a time, determine whether the program
 * will terminate.
 * The solution is as follows:
 * We can simply simulate the execution of the program, one instruction at a time.
 * If at any point we reach a instruction that has already been executed,
 * then we know that the program will terminate.
 * We can keep track of the instructions that have been executed using a Set.
 * @author ilyaberns

public class Solution {
    public boolean isTerminated(int[] program) {
        // keep track of which instructions have been executed
        Set executed = new HashSet<>();
        // start at the first instruction
        int i = 0;
        // continue until we reach the end of the program
        while (i < program.length) {
            // if we've already executed this instruction, then the program will terminate
            if (executed.contains(i)) {
                return true;
            // otherwise, execute the instruction and add it to the set of executed instructions
            i = program[i];
        // if we reach this point, then the program did not terminate
        return false;
class Solution:
    def calculate(self, s: str) -> int:
        # The input string will only contain two numbers and one operator.
        # We can use a stack to keep track of the numbers and operator.
        stack = []
        # Iterate through the string
        for char in s:
            # If the character is a digit, convert it to an int and append it to the stack
            if char.isdigit():
            # If the character is an operator, pop the top two elements from the stack
            # Perform the operation and append the result back to the stack
                num2 = stack.pop()
                num1 = stack.pop()
                if char == '+':
                    stack.append(num1 + num2)
                elif char == '-':
                    stack.append(num1 - num2)
                elif char == '*':
                    stack.append(num1 * num2)
                elif char == '/':
                    stack.append(num1 // num2)
        # The final result will be the top element of the stack
        return stack[-1]
// This is a leetcode problem for a single-threaded CPU. The goal is to // calculate the average wait time for a process. The input is an array // of process objects, each with a name and a time (in milliseconds) // required to complete the process. The output should be the average // wait time for all processes. 

// We can calculate the average wait time by iterating through the array // of processes and calculating the wait time for each one. The wait time // for a process is the sum of the times for all the processes that come // before it in the array. 

function averageWaitTime(processes) {
    let totalWaitTime = 0;
    for (let i = 0; i < processes.length; i++) {
      const process = processes[i];
      let waitTime = 0;
      for (let j = 0; j < i; j++) {
        waitTime += processes[j].time;
      totalWaitTime += waitTime;
    return totalWaitTime / processes.length;
class Solution {
    int singleThreadedCPU(int n, int speed) {
        // your code goes here
        return (n*speed);
using System; 

public class Solution { 

// this method simulates a single-threaded CPU 
// the time complexity of this method is O(n) where n is the number of instructions 
public static int[] ExecuteInstructions(int[] instructions) { 

// check for null or empty input 
if (instructions == null || instructions.Length == 0) { 
return null; 

// create an array to store the results of the instructions 
int[] results = new int[instructions.Length]; 

// execute each instruction and store the result 
for (int i = 0; i < instructions.Length; i++) { 
results[i] = ExecuteInstruction(instructions[i]); 

return results; 

// this method simulates the execution of a single instruction 
// the time complexity of this method is O(1) 
private static int ExecuteInstruction(int instruction) { 

// if the instruction is 0, then we halve the number 
if (instruction == 0) { 
return instruction / 2; 

// if the instruction is 1, then we triple the number and add 1 
if (instruction == 1) { 
return (instruction * 3) + 1; 

// if the instruction is not 0 or 1, then we return -1 
return -1; 

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]