It can be done faster, in O(n) time, if the constraints on start and finish time is low. We can make a dp array, in which for each job, we will do dp[job[i].start]+=1 and dp[job[i].end+1]-=1. After calcualting prefix array from it, maximum number will be our answer. This question is very much similar to the minimum number of lecture halls. For more details, you can refer https://www.geeksforgeeks.org/minimum-halls-required-for-class-scheduling/.

Answer from Vivek on Stack Overflow
🌐
HackerRank
hackerrank.com › challenges › task-scheduling › problem
Task Scheduling | HackerRank
With the first three tasks, the optimal schedule can be: time 1 : task 2 time 2 : task 1 time 3 : task 3 time 4 : task 1 time 5 : task 3 time 6 : task 3
🌐
LeetCode
leetcode.com › problems › task-scheduler
Task Scheduler - LeetCode
You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a ...
🌐
GitHub
github.com › ningke › tasksched
GitHub - ningke/tasksched: HackerRank's Task Scheduling Problem · GitHub
Task i is specified by the deadline by which you have to complete it (Di) and the number of minutes it will take you to complete the task (Mi). You need not complete a task at a stretch.
Starred by 9 users
Forked by 2 users
Languages   Python
🌐
HackerRank
hackerrank.com › challenges › task-scheduling › topics
Programming Problems and Competitions :: HackerRank
Join over 30 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.
🌐
HackerEarth
hackerearth.com › practice › algorithms › greedy › basics-of-greedy-algorithms › practice-problems › approximate › process-scheduling-34fa1bb3
Process Scheduling | Practice Problems
Prepare for your technical interviews by solving questions that are asked in interviews of various companies. HackerEarth is a global hub of 5M+ developers. We help companies accurately assess, interview, and hire top developers for a myriad of roles.
🌐
HackerRank
hackerrank.com › challenges › jesse-and-os-1 › problem
Jesse and OS 1 | HackerRank
Jesse is building his own operating system and now faces the task of building the process scheduling and the memory management feature. He has laid down the rules of how he is going to do it.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › minimum-time-required-to-schedule-k-processes
Minimum time required to schedule K processes - GeeksforGeeks
June 30, 2023 - Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Top answer
1 of 2
1

I guess you are missing the cases, where there are multiple jobs starting in the same time and all of them could be completed before the next job starts which is very small.

For example,

5
0 3
0 2
0 4
10 2
10 1

should enqeue first 3 items and process all of them before enqeuing other 2 items. This case will fail in your case.

Other observation:

The for loop for arranging the vector based in cooktime is not needed and coded wrongly.

for(long long i=0;i<n-1;i++)
{
    if(c[i].arrTime==c[i+1].arrTime && c[i].cookTime>c[i].cookTime)
    {
        swap(c[i],c[i+1]);
    }
}

It must be 'c[i].cookTime>c[i+1].cookTime' The priority queue ensure that you get the least cooktime from given set

A working solution passing all cases written in python is given below for reference.

import heapq

def getAvgWaitTime(n, cust):
    heap = []
    curTime = 0
    waitTime = 0
    cust = sorted(cust)
    i = 0

    while i < n:
        if curTime < cust[i][0]:
            curTime = cust[i][0]
        while i < n and (curTime >= cust[i][0]):
            heapq.heappush(heap, (cust[i][1], cust[i][0]))
            i += 1

        while (i < n) and curTime < cust[i][0] and len(heap) > 0:
            time, wait = calculateWaiting(heap, curTime)
            curTime += time
            waitTime += wait

    # Clear all the jobs
    while len(heap) > 0:
        time, wait = calculateWaiting(heap, curTime)
        curTime += time
        waitTime += wait

    return waitTime / n


def calculateWaiting(heap, curTime):
    wait = 0
    cur = heapq.heappop(heap)
    wait = curTime - cur[1] + cur[0] 
    return (cur[0], wait)


n = int(raw_input().strip())
cust = []
for i in range(n):
    ar = map(int, raw_input().strip().split(' '))
    cust.append((ar[0], ar[1]))


result = getAvgWaitTime(n, cust)
print result

Hope it helps!

2 of 2
1

Explanation

First, a short explanation on important aspects of the problem.

  1. Orders may not come in the right order, meaning they may not be sorted by arrival time. So, make sure to sort them by arrival time first.
  2. It's important to realise that out of waiting orders, the cook must pick the one with the minimum cooking time. This way, the resulting waiting time will always be minimal.
  3. Additionally, if there are no orders for the cook to process, the "current" time can be played out till the next arriving order.

Code

In addition to the accepted answer, a C++ solution (since the question is marked with a C++ tag) may look as below.

#include <bits/stdc++.h>

using namespace std;

struct customer {
    uint64_t arrivalTime;
    uint64_t cookingTime;    
};

/*
 * Complete the minimumAverage function below.
 */
uint64_t minimumAverage(std::deque<customer> clients, uint32_t numberOfClients) {
    auto compareByArrivalTime = 
            {
                return client1.arrivalTime < client2.arrivalTime;
            };
    
    auto compareByCookingTime = 
            {
                return client1.cookingTime > client2.cookingTime;
            };
    
    std::sort(clients.begin(), clients.end(), compareByArrivalTime);
    
    std::priority_queue<customer, std::vector<customer>, decltype(compareByCookingTime)> clientPriorityQueue(compareByCookingTime);
    
    uint64_t minWaitingTime = 0;
    uint64_t currentTime = clients.front().arrivalTime;
    for (auto servedClient = 1; servedClient <= numberOfClients; servedClient++) {
        while (!clients.empty() && currentTime >= clients.front().arrivalTime) {
            clientPriorityQueue.push(clients.front());
            clients.pop_front();
        } 
        
        customer bestClient = clientPriorityQueue.top();
        clientPriorityQueue.pop();
        
        uint64_t arrivalTime = bestClient.arrivalTime;
        uint64_t cookingTime = bestClient.cookingTime;
        minWaitingTime += (currentTime - arrivalTime + cookingTime);
        currentTime += cookingTime;
        
        if (!clients.empty()) {
            currentTime = std::max(currentTime, clients.front().arrivalTime);    
        }
    }
    
    return minWaitingTime / numberOfClients;
}

int main()
{
    uint32_t n;
    std::cin >> n;

    std::deque<customer> clients;
    for (auto i = 0; i < n; i++) {
        customer client;
        std::cin >> client.arrivalTime >> client.cookingTime;
        clients.push_back(client);
    }

    uint64_t result = minimumAverage(clients, n);

    std::cout << result << "\n";

    return 0;
}
Find elsewhere
🌐
Brainly
brainly.in › computer science › secondary school
Task scheduling hackerrank solution - Brainly.in
June 16, 2023 - Python code that demonstrates a basic implementation of the task scheduling algorithm using a topological sort:
🌐
TheCScience
thecscience.com › home › hackerrank task scheduling problem solution
HackerRank Task Scheduling Problem Solution
May 13, 2023 - Output T lines. The i line contains the value of the maximum amount by which a task’s completion time overshoots its deadline, when the first tasks on your list are scheduled optimally.
🌐
HackerEarth
hackerearth.com › problem › algorithm › vidurs-job-scheduling
Vidur's Job Scheduling | Practice Problems
Prepare for your technical interviews by solving questions that are asked in interviews of various companies. HackerEarth is a global hub of 5M+ developers. We help companies accurately assess, interview, and hire top developers for a myriad of roles.
🌐
HackerRank
hackerrank.com › skills-directory › operating_systems
Operating Systems | Skills Directory | HackerRank
Proficiency in the foundational concepts of operating systems, including process management, memory management, file systems, and device management. Understanding of kernel-mode and user-mode execution, as well as the mechanisms that enable multitasking and resource allocation. ... Expertise in task scheduling algorithms, such as Round Robin, First-Come-First-Served, Shortest Job Next, and priority-based scheduling.
🌐
YouTube
youtube.com › nick white
LeetCode 621. Task Scheduler (Algorithm Explained) - YouTube
(Technical Interview Study Guide Available) Patreon - https://www.patreon.com/nick_white?al... ___ Discord - https://discord.gg/2f2Tgy3 Twitch - https://www....
Published   January 13, 2020
Views   19K
🌐
HackerEarth
hackerearth.com › problem › algorithm › robin-robin-round-robin-5
Robin Robin, Round Robin! | Practice Problems
Prepare for your technical interviews by solving questions that are asked in interviews of various companies. HackerEarth is a global hub of 5M+ developers. We help companies accurately assess, interview, and hire top developers for a myriad of roles.
🌐
GitHub
github.com › topics › process-scheduler
process-scheduler · GitHub Topics · GitHub
Completion Time, Turnaround Time, Waiting Time, and Response Time for comparative purpose of scheduling algorithms. scrutinizing their performance metrics to optimize task scheduling processes · scheduling round-robin fcfs operating-systems process-scheduler sjf cpu-scheduling timeline-chart srtf hrrn lrtf ljf
🌐
GitHub
github.com › theli-ua › derp › blob › master › HackerRank › task-scheduling.cpp
derp/HackerRank/task-scheduling.cpp at master · theli-ua/derp
Some random derps and snippets. Contribute to theli-ua/derp development by creating an account on GitHub.
Author   theli-ua
🌐
YouTube
youtube.com › neetcode
Task Scheduler - Leetcode 621 - Python - YouTube
🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews🥷 Discord: https://discord.gg/ddjKRXPqtk🐦 Twitter: https://twitter.com/neetcode1🐮 S...
Published   November 27, 2021
Views   166K
🌐
AlgoMonster
algo.monster › liteproblems › 2895
2895. Minimum Processing Time - In-Depth Explanation
In-depth solution and explanation for LeetCode 2895. Minimum Processing Time in Python, Java, C++ and more. Intuitions, example walk through, and complexity analysis. Better than official and forum solutions.