LeetCode 729 My Calendar I (Explain Python Solution)

Python Solution:


from sortedcontainers import SortedList

class MyCalendar:

    def __init__(self):
        self.calendar = SortedList()
        
        #[10,20],[20,30],[35,38],[40,50]
        #

    def book(self, start: int, end: int) -> bool:
        #Use binary search to find the index, time complexity: O(logN)
        index = self.calendar.bisect_right((start,end))
        if(index>0 and self.calendar[index-1][1]>start) or (index<len(self.calendar) and self.calendar[index][0]<end):
            return False
        else:
            self.calendar.add((start,end))
            return True

    #Time Complexity: O(nlogn)
    #Space Complexity: O(n)


# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)

 

Time Complexity: O(NlogN)

Space Complexity: O(N)


Feeling tired? You can also try our free online no-installation required casual games: Here Please consider to follow my youtube channel to support me: