Task Scheduler - Leetcode 621 - Python

  Рет қаралды 146,610

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: / discord
🐦 Twitter: / neetcode1
🐮 Support the channel: / neetcode
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
💡 BINARY SEARCH PLAYLIST: • Binary Search
📚 STACK PLAYLIST: • Stack Problems
Problem Link: neetcode.io/problems/task-sch...
0:00 - Read the problem
4:05 - Intuition
6:52 - Explaining Solution
11:45 - Coding Solution
leetcode 621
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#task #scheduler #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 127
@symbol767
@symbol767 Жыл бұрын
After coming back to this video like 10 times over the course of a month or 2 (giving up constantly on this problem), I finally came back today, listened to you explain the solution, after you explained it I didn't watch the coding this time and just tried it myself and it made sense. Finally progress...
@dingus2332
@dingus2332 11 ай бұрын
I feel thats the thing with these problems , if you know a problem then you know it instantly and will have an initial intuition , but if you dont then I guess you just dont , its better to keep aside the ego and just watch all the solutions possible
@RoninCunningham
@RoninCunningham 2 жыл бұрын
Not the hero we deserve, but the hero we need
@deathstrokebrucewayne
@deathstrokebrucewayne 2 жыл бұрын
Your content is just wow ! The best there exists..Crisp...precise yet detailed ! And directly goes in the mind :)
@b9944236
@b9944236 Жыл бұрын
There are many high votes solutions in Leetcode , but I just can't understand the concept behind their fancy solution. Fortunately, I found this great video and could nearly solve it by myself. Thanks a lot.
@binay_krishn
@binay_krishn 2 жыл бұрын
your explanation skills i found is bestest in the entire youtube
@parvezrafi4098
@parvezrafi4098 Жыл бұрын
This is one of best explanations I found for the problem. Thank you NeetCode!
@sharwariphadnis1298
@sharwariphadnis1298 3 ай бұрын
This is probably one of the most intuitive solutions I have seen for the Task Scheduler problem. Keep up the great work!
@jnayehsirine6222
@jnayehsirine6222 Ай бұрын
do u know what intuitive mean ?
@dilmurodabdusamadov5572
@dilmurodabdusamadov5572 3 ай бұрын
Thank you! I'd never be able to come up with this solution myself during the interview.
@brianevans4975
@brianevans4975 2 жыл бұрын
Sweet, this was my solution. Didn't see it in the official Leetcode solutions, but it made so much sense.
@jasonswift7468
@jasonswift7468 Жыл бұрын
That's very intuitive solution we can use in the interview. Great.
@jasonguo7596
@jasonguo7596 Жыл бұрын
This is so clearly explained. Thank you!
@josembass
@josembass 2 жыл бұрын
As always, great explanation. This was great to explain greedy algorithms. I'm somewhat concerned that still I'm not be able to figure out this approaches without some hints.
@depthsofabjection
@depthsofabjection Жыл бұрын
yeah idk how the fuck people come up with this shit i got close in my thinking to using a queue but then figured there's no way that we're using yet another datastructure for this problem and of course i am wrong yet again
@haoli8983
@haoli8983 6 күн бұрын
i have the same concerns.... if i didn't code the problem before. i think i can't finish this :( maybe just use force brute....
@netraamrale3850
@netraamrale3850 11 ай бұрын
You are amazing...!!! Thanks for making this content available for free. Really helps a lot...!!!
@n.h.son1902
@n.h.son1902 11 күн бұрын
Thanks to you, from your drawing solution I can get to the coding solution pretty easily
@CarlJohnson-iv7sn
@CarlJohnson-iv7sn Жыл бұрын
Man, this is so hard. I also saw a math or greedy solution in the solution section. Will I ever get a good job :'(
@healing1000
@healing1000 Жыл бұрын
Thank you. As you said this is intuitive.
@RohitKumar-dy2gc
@RohitKumar-dy2gc Жыл бұрын
amazing and very simple approach
@ekhobbies1877
@ekhobbies1877 2 жыл бұрын
the only time you need to idle cpu is when there is no enough smaller tasks to fill the gaps! There for the result would be the maximum of either the total number of tasks or (maxTask * (1 + idleTime) - idleTime + howManyTimesTheMaxIs repeated ! (tested it on leetcode and got accepted)
@mirceanicolaescu9804
@mirceanicolaescu9804 2 жыл бұрын
Smart! This is a better solution than in the video.
@amirtv106
@amirtv106 2 жыл бұрын
Could you explain?
@dodziraynard
@dodziraynard Жыл бұрын
This genius but how will I be able to come up with this in an interview? def leastInterval(self, tasks: List[str], n: int) -> int: maxTask = max(Counter(tasks).values()) maxRepeats = Counter(Counter(tasks).values())[maxTask] return max(len(tasks), maxTask * (1 + n) - n + maxRepeats - 1)
@quanghuyluong1249
@quanghuyluong1249 5 ай бұрын
@@amirtv106 In the video around 8:00 to 9:45, he's explaining the process of popping the max from the heap, adding to the queue and popping from queue then adding back to the heap. Notice that when the max value is popped from the heap, it is always gonna be added back being the greatest value in the heap. Why? Because in that one cooldown interval, every other value is gonna be reduced at most one before the max is removed from queue and added to the heap (once they are processed - reduced the count by one - they are going to the queue standing after the max (because the max is added first)). There's no jump in the order. So, once a max, always a max.
@rahuldey1182
@rahuldey1182 Жыл бұрын
Neetcode is the Mozart of LeetCode.
@hyungminkim6664
@hyungminkim6664 2 жыл бұрын
Hi NeetCode, thanks for the content. By the way, do you know when I need to heapify the heap and when I do not need to? I am thinking if I have to just push elements into the heap, then I don't need to heapify, but when I am popping from the heap, then I need to heapify the heap first?
@NeetCode
@NeetCode 2 жыл бұрын
The main rule is, if you have all of the elements available at the beginning, then you should run Heapify - O(n) time, if you don't have all of the elements available immediately, then you will have to separately push each one to the Heap - O(n*logn) time.
@nintendolover82
@nintendolover82 Жыл бұрын
This should be a hard.
@jormanbustos7877
@jormanbustos7877 2 жыл бұрын
Would it work with an ordered deck instead of a maxHeap?
@Mohammad-wo7yi
@Mohammad-wo7yi Жыл бұрын
I think the total time complexity of the final code should be O(n * len(tasks)) since we are iterating over all time slots available. So if we have a task array of [A, A, A, A] then the total number of loops will equal to n * len(tasks).
@boiimcfacto2364
@boiimcfacto2364 11 ай бұрын
He mentions this at 14:00 btw
@Grawlix99
@Grawlix99 Жыл бұрын
Optimized the code some. We can sort a single time and then simply use a deque() to avoid repeatedly pushing/popping from heap. It also really simplifies the internals of the while loop, since we don't need to track both a heap and a queue. def leastInterval(self, tasks: List[str], n: int) -> int: if n == 0: return len(tasks) # Sort the array in order of max frequency count = Counter(tasks) frequencies = list(count.values()) frequencies.sort(reverse=True) # For each frequency, associate it with the time at which it can be ran. Use +1 to offset 0-indexing jobs = deque([i+1, j] for i, j in enumerate(frequencies)) # Start the time variable at 0, so once we enter the loop we will be at time '1' # This allows us to directly return time at the end. time = 0 while jobs: time += 1 if time < jobs[0][0]: # The next task is not yet ready to run (still on cooldown) so wait one unit of time continue # The task is ready to run, so pop from the queue* and adjust its frequency cur_turn, cur_freq = jobs.popleft() cur_freq -= 1 if cur_freq > 0: jobs.append([cur_turn + n + 1, cur_freq]) return time
@def__init
@def__init Жыл бұрын
You meant to say pop from queue not heap. Btw good explanation thanks!
@xmnemonic
@xmnemonic Жыл бұрын
This is better than neetcode's solution.
@msinkusmeowmeow1442
@msinkusmeowmeow1442 11 ай бұрын
But, isn’t O(n) time complexity better than O(nlogn) ( sorting a list)
@Grawlix99
@Grawlix99 11 ай бұрын
@@msinkusmeowmeow1442 Heap operations are Log N. It's been a while since I looked at this problem, but if Neetcode potentially has a heap operation for every element, it's O(N*logN).
@msinkusmeowmeow1442
@msinkusmeowmeow1442 11 ай бұрын
@@Grawlix99maybe you forgot, cause you commented 10 months ago. But in this problem we have log26 constant operation for heap , and since we heapify out list the time complexity is O(n) linear . The question I asked now is that in your solution you used sort(), which is O(nlogn) and which is worse than O(n)
@stith_pragya
@stith_pragya 9 ай бұрын
Thank You So Much for this wonderful video...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@rostislav_vat
@rostislav_vat 3 ай бұрын
thanks for this video!
@srinadhp
@srinadhp 2 жыл бұрын
Thank you!
@whonayem01
@whonayem01 2 жыл бұрын
Nice solution!
@Douglasfaparanhos
@Douglasfaparanhos 2 жыл бұрын
Very good 👏👏👏
@nurbolatsansyzbay9998
@nurbolatsansyzbay9998 9 ай бұрын
I like how you say "this is pretty efficient solution" while showing 18% faster result xD
@XxM1G3xX
@XxM1G3xX Ай бұрын
I don't think you can say O(log26) for the maxHeap, since it's not just one appearance per letter, it is task.length < 10^4, so there could be 10^4 pops * idle queue
@krishnavamsichinnapareddy
@krishnavamsichinnapareddy Жыл бұрын
Superb explanation
@asdfasyakitori8514
@asdfasyakitori8514 8 ай бұрын
Great video
@SOMESHKHANDELIA
@SOMESHKHANDELIA 12 күн бұрын
This has to be a Leetcode HARD
@stephanembatchou5300
@stephanembatchou5300 2 жыл бұрын
isn't time complexity eq to (N + N*log(N))? because at worst case you have to do up_heapify each time you pop() and insert.
@nlke182
@nlke182 2 жыл бұрын
Yeah the runtime is wrong. You are correct.
@Sportamrina
@Sportamrina 2 жыл бұрын
no because it takes constant time as there are only 26 letters in the alphabet
@demaxl732
@demaxl732 5 ай бұрын
How do people even think of this shit
@numberonep5404
@numberonep5404 2 жыл бұрын
Very cool pb i think
@bobbrown1001
@bobbrown1001 2 жыл бұрын
What is the intuition behind using the queue? Thanks love your videos
@LaithBasilDotNet
@LaithBasilDotNet 2 жыл бұрын
Once you pick a task, you need to put it in a waiting Queue and later if current time >= waiting queue top, if so, we remove this task and return it to the priority queue for another chance to be picked up.
@CongNguyen-og3iz
@CongNguyen-og3iz Жыл бұрын
@@LaithBasilDotNet Thanks for the answer. Really appreciate it.
@Sulerhy
@Sulerhy 3 ай бұрын
@@LaithBasilDotNet thank you so much
@rahulsbhatt
@rahulsbhatt 8 ай бұрын
Hey, NeetCode or Viewers, I have a doubt, according to the code 16:30 After we push elements to the heap, don't we have to heapify it?
@ArjitGuptaAG
@ArjitGuptaAG 8 ай бұрын
No, because heappush takes care of heapifying it internally.
@lakshyagupta411
@lakshyagupta411 8 ай бұрын
Hey...your explanation is excellent and very intuitive. But it is not the most optimized solution. Can you please help me by explaining the optimized approach to solving this problem?
@purerealm
@purerealm Жыл бұрын
How come if the first element in the queue == time, you push it back into the heap? This part feels non-intuitive, shouldn't you be processing this element and subtracting the count instead?
@hoangvietng7100
@hoangvietng7100 3 ай бұрын
thanks bro
@tapojitpaul2104
@tapojitpaul2104 Жыл бұрын
How come the complexity be O(n), n --> Number of characters, when you are iterating through the time required?
@gauravmalvi8115
@gauravmalvi8115 Жыл бұрын
Some one please explain me , why the Time Complexity is O(n) in detail?
@pcccmn
@pcccmn 9 ай бұрын
damn. This question is hard af hahaha
@prashanthkurella4500
@prashanthkurella4500 5 ай бұрын
Do we really need a heap for this? since the number of letters are fixed, we can get away with using sorting the array at every time step as well.
@activelylazy9993
@activelylazy9993 Жыл бұрын
Why the solution is not O(nlogn), as while loop is run n times and in each loop there is a heappop or heappush (logn), ignoring the idle time for simplicity sake?
@Drozerix
@Drozerix Жыл бұрын
The heap push and pop is not log(n) in this case -- it's log(26) because there are 26 letters. As N grows the number of letters in the alphabet remain the same. That is to say the array [2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] (2 As and a count of 1 for every other letter) is the same size as [15432, 67567, 2343345, 67567, 3453, 1231, 5646, 23435, 5675, 45345, 98789, 4535,5435,5436,7776,14324,534,765,3454,786,5434,3456,45654,765,8768,654] (a large count for each letter).
@AyushGupta-ll5rg
@AyushGupta-ll5rg Жыл бұрын
Is the time complexity (tasks.size * n)?
@rm0ndo
@rm0ndo 3 ай бұрын
Why do we increment the time first? Why not on the last line of the loop?
@balasubramanie5354
@balasubramanie5354 3 ай бұрын
Because at time 1 only the tasks starts like at 0 it is in rest State no work is done
@JTMusic880
@JTMusic880 Жыл бұрын
Why is this not O(nlogn)? The time complexity of heappop and heappush are both O(logn), and you perform them N number of times
@vudat1710
@vudat1710 Жыл бұрын
you can basically ignore the logn part because it should be log(26) since we only have 26 characters in the alphabet
@uniquename2386
@uniquename2386 Жыл бұрын
Why is time complexity not O(nlogn)? Can anyone explain why log26 is constant
@degamer106
@degamer106 Жыл бұрын
It's because we're inserting the frequencies of each letter from A-Z into the heap. Since there are only 26 letters in the alphabet, it means the time complexity for the heap pop/push will become log 26 so O(n log 26) -> O(n)
@Sulerhy
@Sulerhy 3 ай бұрын
I watched this video 10 times, and could not understand what is the purpose of a queue and why it is Time + n. Took from me 1 (holi)day. Anyway, your video is still the best. How difficult to explain the process of this question
@johnangelo2000
@johnangelo2000 5 ай бұрын
hmm there is a linear solution Just by frequency make slots and fit all remaining lower frequency slots there.
@008manasvikothlapuram2
@008manasvikothlapuram2 11 ай бұрын
i did this and im getting time limit exceeded why??
@ghazanferwahab5673
@ghazanferwahab5673 Жыл бұрын
Java Solution: class Solution { class Pair{ int rem_time; int next; Pair(int rem_time,int next){ this.rem_time=rem_time; this.next=next; } } public int leastInterval(char[] tasks, int n) { int cnt[]=new int[26]; for(char c:tasks) cnt[c-'A']++; PriorityQueueq=new PriorityQueue((a,b)->b-a); for(int i=0;i0){ q.add(cnt[i]); } } Queueq1=new LinkedList(); int time=0; while(q.size()>0||q1.size()>0){ time++; if(q.size()>0){ int cur=q.poll(); cur--; if(cur>0) q1.add(new Pair(cur,time+n)); } if(q1.size()>0 && q1.peek().next==time && q1.peek().rem_time>0){ Pair d=q1.poll(); q.add(d.rem_time); //if we use the below approach the time span of one of the values is never reached as the time is 1 and current time is already>1 // System.out.println(d.rem_time+" "+d.next); // if(d.rem_time>0) // q1.add(new Pair(d.rem_time,time+n)); } } return time; } }
@PedanticAnswerSeeker
@PedanticAnswerSeeker 3 ай бұрын
Here is another way to do the same task_counts = {} for task in tasks: task_counts[task] = task_counts.get(task, 0) + 1 max_occurence = max(task_counts.values()) tasks_with_max_occurrences = sum(1 for count in task_counts.values() if count == max_occurence) min_time_needed = (max_occurence - 1) * (n + 1) + \ tasks_with_max_occurrences return max(min_time_needed, len(tasks))
@victorcui4014
@victorcui4014 Жыл бұрын
what is the space complexity of this solution?
@brianwang5660
@brianwang5660 Жыл бұрын
Hello, I believe it's O(1), but do correct me if I am wrong. Hashmap -> at most 26 elements at a time PQ -> at most 26 elements at a time Queue -> at most 26 elements at a time So O(26 + 26 + 26) ~= O(1)
@jewelchakraborty9717
@jewelchakraborty9717 3 ай бұрын
Is this question actually hard or is it just me? Because I tend to forget the solution multiple times.
@paulabboud3321
@paulabboud3321 2 жыл бұрын
What program do you use to draw out the solution?
@NeetCode
@NeetCode 2 жыл бұрын
I use Paint3D with a mouse
@hhcdghjjgsdrt235
@hhcdghjjgsdrt235 Жыл бұрын
Ive tried myself and also tried some codes from discuss section. none of them showed more than 20 to 25 % faster rate. edit: i m using C#
@anyangli918
@anyangli918 Жыл бұрын
the code is run at a container so the code performance varies each time
@hhcdghjjgsdrt235
@hhcdghjjgsdrt235 Жыл бұрын
@@anyangli918 okay sir
@sauravchandra10
@sauravchandra10 11 ай бұрын
2 3 months before, I could not understand your videos and referred to Indian creators, but once I reached a certain level, I can now understand your solutions and code it up in C++.
@Area-fd8ht
@Area-fd8ht 11 ай бұрын
Bhai ye bhi indian hi h.. Lekin eksa acent itna sexy hai ki angrez lagta h😅
@sauravchandra10
@sauravchandra10 11 ай бұрын
@@Area-fd8ht LOL didnt know that!
@Area-fd8ht
@Area-fd8ht 11 ай бұрын
Es question ka code mil jayega c++ ka
@adityahpatel
@adityahpatel 2 ай бұрын
There is no way anyone with reasonable IQ can conceive this method for the 1st time if they had not memorized this before.
@technosarthak15
@technosarthak15 2 ай бұрын
Here is the C++ solution for the above logic class Solution { public: int leastInterval(vector& tasks, int n) { vector taskCounts(26, 0); for (char task : tasks) { taskCounts[task - 'A']++; } priority_queue pq; for (int count : taskCounts) { if (count > 0) { pq.push(count); } } queue q; int time=0; while(!pq.empty() || !q.empty()) { time++; if(!pq.empty()) { int val=pq.top(); pq.pop(); if(val-1!=0) { q.push({val-1,time+n}); } } if(!q.empty() && time==q.front().second) { pq.push(q.front().first); q.pop(); } } return time; } };
@sdegueldre
@sdegueldre Жыл бұрын
I'm quite interested in the optimal solution that you mention exists at the end. Is there a closed form solution? Also I think it's dishonest to disregard terms during the complexity analysis because the problem statement puts bounds on it, ie you say "it's O(n*log(26)) because the task type is an uppercase English letter". Well yeah, the problem also states that the task length is
@vansharora9027
@vansharora9027 Жыл бұрын
My general rule of thumb is to treat any charset size as a constant. When dictating complexity, we only care for extremely large approaching infinite numbers. The user input is limited to the cooldown and task length. The problem itself does not consider which character set the user wishes to choose, regardless it will contribute constant time. If tasks could be integers, then this problem could be much more difficult to solve. As the "charset" for integers is infinite.
@firomsamt7642
@firomsamt7642 5 ай бұрын
damn! wow
@CANIHAZURDREAMSPLS
@CANIHAZURDREAMSPLS 9 ай бұрын
How does Leetcode come up with these questions lol
@zijiali8349
@zijiali8349 3 ай бұрын
Fuck the people in Google who does nothing but torture interviewees.
@johnnychang3456
@johnnychang3456 Жыл бұрын
This problem should be hard. Jesus.
@yashrajprasad6076
@yashrajprasad6076 3 ай бұрын
How can I do the same by using positive counts in max heap?
@keerthivasan138
@keerthivasan138 Жыл бұрын
Sir Is there is any way without using queue
@HD-xn1br
@HD-xn1br Жыл бұрын
Am I crazy or did you not explain how to handle an idle in the "Explaining Solution" section? You just explained an ideal case where no tasks require idling
@RohitKumar-dy2gc
@RohitKumar-dy2gc Жыл бұрын
yeah you are he does ,idle time increments when heap is empty but queue is not
@pranavsharma7479
@pranavsharma7479 2 жыл бұрын
why its going time limit exceeded? int leastInterval(vector& tasks, int n) { unordered_map mpp; for(auto task : tasks){ mpp[task]++; } priority_queue maxh; for(auto i : mpp){ maxh.push(i.second); } queue q; int time = 0; while(maxh.size() > 0 or q.size() > 0){ if(maxh.size() > 0){ int count = maxh.top(); maxh.pop(); time += 1; --count; if(count != 0) { q.push({count,time+n}); } } if(q.size() > 0 and q.front().second == time){ auto temp = q.front(); maxh.push(temp.first); q.pop(); } } return time; }
@brianmoon6310
@brianmoon6310 2 жыл бұрын
You are only incrementing time if(maxh.size() > 0) but you need to increment time for every iteration of your while loop :) So just put time += 1 as the first line after your while statement
@indsonusharma
@indsonusharma Жыл бұрын
Working code for the same!!. class Solution { public: int leastInterval(vector& tasks, int n) { unordered_map mpp; for(auto task : tasks){ mpp[task]++; } priority_queue pq; for(auto i : mpp){ pq.push(i.second); } queue q; int time = 0; while(pq.size() > 0 or q.size() > 0){ if(pq.size() > 0){ int count = pq.top(); pq.pop(); time += 1; --count; if(count != 0) { q.push({count,time+n}); } } if(q.size() > 0 and q.front().second
@alexzander__6334
@alexzander__6334 2 жыл бұрын
heapq is not defined, where is located heapq ?
@NeetCode
@NeetCode 2 жыл бұрын
It works by default for me, but you might have to add "import heapq"
@alexzander__6334
@alexzander__6334 2 жыл бұрын
@@NeetCode oh, so its import, i didnt see the import in the video, thats why i asked. thanks
@princeanthony8525
@princeanthony8525 8 ай бұрын
Seriously dude, don’t you have a better solution than this ?
@marufm8195
@marufm8195 2 жыл бұрын
I can't be bothered
@quanghuyluong1249
@quanghuyluong1249 5 ай бұрын
I want to leave a note why the true linear (and greedy) solution is possible and how it could be intuitive. In the video around 8:00 to 9:45, he's explaining the process of popping the max from the heap, adding to the queue and popping from queue then adding back to the heap. Notice that when the max value is popped from the heap, it is always gonna be added back being the greatest value in the heap. Why? Because in that one cooldown interval, every other value is gonna be reduced at most one before the max is removed from queue and added to the heap (once they are processed - reduced the count by one - they are going to the queue standing after the max (because the max is added first)). There's no jump in the order. So, once a max, always a max. After we've got this info, we can just get rid of both the heap and queue, and go with our greedy approach.
@Nightaxeblade
@Nightaxeblade 6 ай бұрын
Should have just not used python, to keep it simple
@JohnDoe-mr6mq
@JohnDoe-mr6mq 8 ай бұрын
Didn't like that explanation coupled to python implementation of a heap
@pdjeowudjx
@pdjeowudjx 3 ай бұрын
such a bad question
@johnpaul4301
@johnpaul4301 Жыл бұрын
Dude I know you are a python god but please just use normal syntax so everybody else dont have a headache trying to decode what a line means
@messi_codes
@messi_codes 3 ай бұрын
I QUIT!
@DavidDLee
@DavidDLee Жыл бұрын
Here is a much more concise and easier to understand solution def leastInterval(self, tasks: List[str], n: int) -> int: n += 1 # n slots from when it finishes, n + 1 from when it started taskMap = {} # task -> last time it ran order = [] clock = 0 for t in tasks: taskMap[t] = c = taskMap.get(t, -n) + n # Will get 0, if not in the map print(f"Taks {t} can start no sooner than @:{c}") heapq.heappush(order, (c, t)) while order: c, t = heapq.heappop(order) clock = max(clock, c) print(f"Starting task:{t} @:{clock}") clock += 1 # 'Executing' the task return clock
@ankurbose7672
@ankurbose7672 10 ай бұрын
Please solve this problem leetcode 855. Exam Room
@yang5843
@yang5843 3 ай бұрын
Anyone get TLE for the java solution? class Solution { public int leastInterval(char[] tasks, int n) { Map map = new HashMap(); for ( char c : tasks) map.put((int)(c-'A'),map.getOrDefault((int)(c-'A'),0)+1); Queue q1 = new PriorityQueue( (a,b) -> b - a ); q1.addAll(map.values()); Queue q2 = new PriorityQueue( (a,b) -> a[0] - b[0] ); int rc =0; while ( !q1.isEmpty() || !q2.isEmpty() ) { rc++; if ( !q1.isEmpty() ) { int count = q1.poll() - 1; if ( count > 0 ) q2.add(new int[]{count,rc+n}); } if ( !q2.isEmpty() && q2.peek()[1] == rc ) { q1.add(q2.poll()[0]); } } return rc; } }
@ameynaik2743
@ameynaik2743 2 жыл бұрын
What is the complexity of heapify in python? is it O(n)
@NeetCode
@NeetCode 2 жыл бұрын
Yeah its O(n)
Subarray Sum Equals K - Prefix Sums - Leetcode 560 - Python
15:19
Design Twitter - Leetcode 355 - Python
22:47
NeetCode
Рет қаралды 74 М.
My little bro is funny😁  @artur-boy
00:18
Andrey Grechka
Рет қаралды 10 МЛН
The child was abused by the clown#Short #Officer Rabbit #angel
00:55
兔子警官
Рет қаралды 17 МЛН
MEU IRMÃO FICOU FAMOSO
00:52
Matheus Kriwat
Рет қаралды 37 МЛН
LeetCode 621. Task Scheduler (Algorithm Explained)
10:29
Nick White
Рет қаралды 61 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 454 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 279 М.
10 Math Concepts for Programmers
9:32
Fireship
Рет қаралды 1,8 МЛН
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 206 М.
Erdős-Woods Numbers - Numberphile
14:12
Numberphile
Рет қаралды 72 М.
My Brain after 569 Leetcode Problems
7:50
NeetCode
Рет қаралды 2,4 МЛН
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 269 М.
ПОКУПКА ТЕЛЕФОНА С АВИТО?🤭
1:00
Корнеич
Рет қаралды 3,3 МЛН
Неразрушаемый смартфон
1:00
Status
Рет қаралды 2 МЛН
Main filter..
0:15
CikoYt
Рет қаралды 12 МЛН
Хотела заскамить на Айфон!😱📱(@gertieinar)
0:21
Взрывная История
Рет қаралды 4,4 МЛН