filmov
tv
Task Scheduler - LeetCode 621 - Python [O(n) time and O(1) Space!]

Показать описание
Explaining how to solve Task Scheduler in Python - LeetCode 621!
(Typo @5:40: should be adding D E F G to the end for output = 10!)
The time complexity for this solution will be O(n). We first iterate through the entire list to keep counts (O(n)). Then, we sort based on the values which typically comes out to O(nlogn) BUT we know that we are only ever sorting 26 letters maximum, so we only need 26 elements to sort and so our n = 26. This makes sorting a constant time operation = 26log26 = constant number not dependent on n, therefore, O(1). After, we iterate again to count how many max values we have that are also our maximum, and this again should be order O(n), but we are only iterating over 26 elements, so we know our while loop will terminate after 26 elements since len(lst) is bounded by 26. And finally, we do constant time calculations, so our overall time complexity is just O(n).
Our space complexity is also O(1) since we only need a dictionary with 26 keys.
** We will never have more than 26 letters so the keys in our dictionary are bound by 26 and therefore so is the length of the lst we maintain.
Music: Bensound
Lemme know if y'all got questions/comments!!
Комментарии