Meeting Rooms II - Leetcode 253 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 14 ต.ค. 2024

ความคิดเห็น • 131

  • @NeetCode
    @NeetCode  3 ปีที่แล้ว +14

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
    Meeting Rooms 1: th-cam.com/video/PaJxqZVPhbg/w-d-xo.html

  • @expansivegymnast1020
    @expansivegymnast1020 ปีที่แล้ว +73

    This is one of those problems that looks really simple until you start actually coding it.

    • @vroomerlifts
      @vroomerlifts 5 หลายเดือนก่อน +3

      I was just asked this in an interview 10 minutes ago. This is similar to N-Fleet problems related to stack. I used a stack to calculate the room numbers.

    • @quirkyquester
      @quirkyquester หลายเดือนก่อน +1

      @@vroomerlifts smart!

  • @rajdeepbiswas8912
    @rajdeepbiswas8912 8 หลายเดือนก่อน +14

    This is a very clever solution, good work on finding it!
    But it's a bit hacky and very specific to this problem, so I feel we are missing out on learning crucial data structures i.e. priority queues
    Perhaps just mentioning it in the video would be pretty helpful!

  • @arnobpl
    @arnobpl 2 หลายเดือนก่อน +3

    Great video! Here is the smaller solution with same time/space complexity as in the video:
    def minMeetingRooms(self, intervals: List[Interval]) -> int:
    timing = []
    for intv in intervals:
    timing.append((intv.start, 1))
    timing.append((intv.end, -1))
    timing.sort()
    result = 0
    ongoing = 0
    for t in timing:
    ongoing += t[1]
    result = max(result, ongoing)

    return result

  • @arjunbharadwaj1820
    @arjunbharadwaj1820 3 ปีที่แล้ว +116

    Very clever solution. I think during an actual interview, I would have come up with a heap solution but not as clever as this.

    • @dingus2332
      @dingus2332 ปีที่แล้ว +7

      Can you give solution from heap ?

    • @nw3052
      @nw3052 ปีที่แล้ว

      @@dingus2332 Have minHeap storing the ends, then while the new interval's start is >= top of the heap, you pop from the heap and then push the new interval's end there. The max size of the heap at any moment is the answer.

    • @IntelliStar_
      @IntelliStar_ 10 หลายเดือนก่อน

      ​@@dingus2332 My heap solution:
      class Solution:
      def minMeetingRooms(self, intervals: List[List[int]]) -> int:
      intervals.sort()
      heap = [intervals[0][1]]

      for i in range(1, len(intervals)):
      if heap[0]

    • @LangePirate
      @LangePirate 10 หลายเดือนก่อน

      @dingus2332
      def min_meeting_rooms(self, intervals: List[Interval]) -> int:
      intervals.sort(key=lambda i : i.start)
      min_heap = []
      rooms = 0
      for i in intervals:
      heapq.heappush(min_heap, i.end)
      while min_heap[0]

    • @EduarteBDO
      @EduarteBDO 9 หลายเดือนก่อน

      @@dingus2332 heap solution:
      def min_meeting_rooms(self, intervals: List[Interval]) -> int:
      if not intervals: return 0
      start,end = [],[]
      for inter in intervals:
      heapq.heappush(start,inter.start)
      heapq.heappush(end,inter.end)
      count,res = 0,0
      while start and end:
      if start[0] < end[0]:
      heapq.heappop(start)
      count+=1
      res=max(res,count)
      else:
      heapq.heappop(end)
      count-=1
      return res

  • @almaskairatuly4422
    @almaskairatuly4422 2 ปีที่แล้ว +25

    Nice trick with 2 arrays for start and end times. One small note here, the code will be a little more efficient if we update the result only when we increase the count (because it's the only time the result can get bigger than whatever it was previously).

  • @aravindravva3833
    @aravindravva3833 6 หลายเดือนก่อน +4

    This can be done multiple ways ,
    1. create an array of max end time .
    2. Then do +1 to the start and -1 for every interval >
    3. Now find the max sum possible at any time .
    TC= O(N) space= O(max(EndTime))

  • @dmytroivanovv
    @dmytroivanovv 3 ปีที่แล้ว +39

    Top explanation of this problem. Thank you, I got the whole point.

  • @tjsm4455
    @tjsm4455 3 หลายเดือนก่อน +1

    Sometimes I narrow down my approach too much, I was trying to solve it using interval techniques but this solution use such a smart 2 pointer approach. Thanks.

  • @shonsanchez6403
    @shonsanchez6403 3 ปีที่แล้ว +16

    You can optimize your solution by only considering the max(res, count) when you are incrementing the count. Since count -1 will never be greater than the previous count.

    • @MaximeAntoine97
      @MaximeAntoine97 2 ปีที่แล้ว

      I was just thinking the same! Looked in the comments to see if I wasn't the only one

  • @jigardoshi1549
    @jigardoshi1549 2 ปีที่แล้ว +7

    Nice explanation - I believe this can be easily solved using a minheap (especially in java where creating Start and End array would take many more lines)
    Here's my solution for java --
    public int minMeetingRooms(int[][] intervals)
    {
    Arrays.sort(intervals, (i1, i2) -> i1[0] - i2[0]);
    var heap = new PriorityQueue((i1, i2) -> i1[1] - i2[1]);
    for (var meeting: intervals) {
    heap.offer(meeting);
    if (heap.peek()[1]

    • @Yuipser
      @Yuipser 2 ปีที่แล้ว +1

      I also came up with the same approach, the time complexity is the same
      we compare the current interval start time with the min(end time) of prev meetings, if start time < min(end times), we cannot start the meeting using the existing rooms, we add a new room (push the current end time)
      else if start time >= min(end times), we can start the meeting in the room with min(end times) (pop from minheap and push the current end time)
      def min_meeting_rooms(self, intervals: List[Interval]) -> int:
      if not intervals:
      return 0
      intervals.sort(key = lambda i: i.start)
      end_times = [intervals[0].end]
      heapq.heapify(end_times)
      for i in intervals[1:]:
      if i.start >= end_times[0]:
      heapq.heappop(end_times)
      heapq.heappush(end_times, i.end)
      return len(end_times)

    • @edk4351
      @edk4351 2 ปีที่แล้ว

      @@Yuipser I believe the time complexity is a little slower? The worse case scenario would be n(log(n) + log(n)) or n(log(n^2)). Each heap push/pop operation takes log(n).

  • @SmoothCode
    @SmoothCode 2 ปีที่แล้ว +15

    Though this solution is super clever, I do not think that I could come up with that during an interview. Please use common algorithms and DS to solve these Leetcode questions.

  • @aismitdas9138
    @aismitdas9138 2 ปีที่แล้ว +7

    I never usually write comments on youtube, but I just had to for this video. But this is a very clear yet clever solution :) !

  • @DontTakeCrack
    @DontTakeCrack 8 หลายเดือนก่อน

    great solution.
    while i was looking at your visual diagram, i followed the same logic but simply inserted all start and end times into one array, sorted it, and differentiated whether or not that time was a start or end time. The sorting just has to make sure that if start == end, then end will go first due to the semi-inclusive nature of the problem.
    then it simply becomes if (t is a start time) num_meeting_rooms += 1; else num_meeting_rooms -= 1
    TLDR: same logic and almost the same code but slightly different

  • @Techgether
    @Techgether 2 หลายเดือนก่อน

    This is my approach, my time complexity is also O(nlogn) and space complexity is O(n) where n is length of intervals elements. The nested loop has an amortized time complexity of O(n), correct me if i'm wrong! My logic is to keep track of any last end that has overlapped, then use each of these new last ends to check against the last start time.
    class Solution:
    def minMeetingRooms(self, intervals: List[Interval]) -> int:
    if not len(intervals): return 0
    intervals.sort(key=lambda i:i.end)
    res = [intervals[0].end]
    for i in range(1,len(intervals)):
    start = intervals[i].start
    end = intervals[i].end
    found = 0
    for j in range(len(res)):
    if res[j]

  • @devdev19
    @devdev19 2 ปีที่แล้ว +13

    I attempted to solve this problem by using an adjacency list and graph traversal to count intersecting intervals but I didn't realize this was a bad approach until I spent a good amount of time pursuing it. How would you recommend being able to notice these incorrect approaches early?

    • @hwang1607
      @hwang1607 ปีที่แล้ว +1

      i also need help with this

    • @rajdeepbiswas8912
      @rajdeepbiswas8912 8 หลายเดือนก่อน +1

      hey buddy, any progress on this?

  • @RaoVenu
    @RaoVenu 2 ปีที่แล้ว +3

    Great explanation. I had an implementation with a Min heap but then I have to implement the minheap in javascript. This is way easier

  • @marhawk6468
    @marhawk6468 3 ปีที่แล้ว +10

    Woooooo this is the one I’ve been waiting for. Many thanks NeetCode!

  • @omeedtehrani2950
    @omeedtehrani2950 23 วันที่ผ่านมา

    This is an insanely clever solution. Thanks for sharing.

  • @deathbombs
    @deathbombs ปีที่แล้ว

    I was going to use priority queue of end times, and int[] of start times, but your approach using int[] for start and end[] is simpler
    Main differences are using a PQ, it sorts as new values are added. No pointers are needed here to manage and no need to create new int arrays

  • @dream11tatyabichoo92
    @dream11tatyabichoo92 3 หลายเดือนก่อน

    The only problem with this is decreasing rooms, which gives a false perception of why we are decreasing rooms, as the rooms will remain same, but in this implementation i will not be increased when we are increasing j, but it will increase again when value at i < j, so in this example if i = 4 it denotes that max has correct number of room upto i =3, and i is still in process, if we increment i in each iteration , then we don't need to do --rooms in else part, which is more intuitive to the users, same as restaurant problem of cses and taking one dimensional array to solve it is more intuitive as it can give the clear picture of how many rooms/ customers are there at any one particular point of time

  • @jinny5025
    @jinny5025 3 ปีที่แล้ว +6

    I really like your videos. Your explanations are so clear that dummies like me also could understand 🤣

  • @rokasnavickas3447
    @rokasnavickas3447 2 หลายเดือนก่อน

    One side note, sorted([i.start for i in intervals]) won't work in leetcode as the intervals is specified as List[List[int]], you'd have to use i[0] for start and i[1] for finish

  • @cc-to2jn
    @cc-to2jn 2 ปีที่แล้ว +1

    Great job as always. I did it slightly different, where I created essentially a stack of meetings. So the output would look something like the example output:
    intervals.sort(key=lambda x:x.start)
    out=[[intervals[0]]]
    for i in range(1,len(intervals)):
    for l in out:
    if l[-1].end

    • @PippyPappyPatterson
      @PippyPappyPatterson 2 ปีที่แล้ว

      oh wow interesting. Is this O(n⋅logn + n) or O(n⋅logn + n²) time?

    • @cc-to2jn
      @cc-to2jn 2 ปีที่แล้ว +1

      @@PippyPappyPatterson Assuming worst case, it would be O(n^2). I don't think you would do O(nLogn+n^2) as the bigger rate of change takes priority. However, on average it likey O(nLogn).
      Not the best with my time complexity analysis, so someone create me if I'm wrong.

    • @PippyPappyPatterson
      @PippyPappyPatterson 2 ปีที่แล้ว

      @@cc-to2jn Sweet, thanks for your thoughts!
      Do you know of any Khan_Academy/Leetcode style problems for evaluating time and space complexity?
      I feel like the only way I'll get better is if I grind out problems w/ immediate, automated feedback like leetcode solutions.

    • @cc-to2jn
      @cc-to2jn 2 ปีที่แล้ว +2

      @@PippyPappyPatterson I am not aware of any such sources. Space and time complexity evaluation you kind of just learn as you do the problems. I would suggest watching some videos on the basics first however. There are a lot of great videos, these 2 are my fav:
      th-cam.com/video/Mo4vesaut8g/w-d-xo.html
      th-cam.com/video/D6xkbGLQesk/w-d-xo.html

    • @PippyPappyPatterson
      @PippyPappyPatterson 2 ปีที่แล้ว

      @@cc-to2jn thanks friend. Happy salary hunting!

  • @namansingh6540
    @namansingh6540 8 หลายเดือนก่อน

    I would also recommend checking out the line sweep algorithm to solve this

  • @SethuIyer95
    @SethuIyer95 6 หลายเดือนก่อน

    I did using fenwick tree, same complexity O(nlogn)

  • @AlfredPros
    @AlfredPros หลายเดือนก่อน

    The alternative solution to this would be similar to LeetCode 435 (Non-overlapping Intervals).
    The additional part is for every interval overlap, would be put to a list, then use that list as a new interval list.
    def minMeetingRooms(self, intervals: List[Interval]) -> int:
    count = 0
    intervals.sort(key=lambda i:i.start)

    while intervals:
    curr = intervals[0]
    count += 1
    new_intervals = []
    for i in intervals[1:]:
    if i.start < curr.end:
    if curr.end > i.end:
    curr = i
    new_intervals.append(curr)
    else:
    new_intervals.append(i)
    else:
    curr = i
    intervals = new_intervals
    return count

  • @fv5895
    @fv5895 2 ปีที่แล้ว

    can anyone elaborate more on while( s < len(intervals)) condition ?

    • @avenged7ex
      @avenged7ex 2 ปีที่แล้ว +1

      if the starting pointer is already outside the length of the array, then that means that only the end intervals can come next. Due to that, the overlaps are only going to start decreasing and the conflicts will decrease. But we're looking for the max, so we can just stop here and avoid the unnecessary work.

  • @stith_pragya
    @stith_pragya 5 หลายเดือนก่อน +1

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @sidhartheleswarapu
    @sidhartheleswarapu 7 หลายเดือนก่อน +1

    Is there a way to do this while keeping track of prevEnd, similar to the non-Overlapping intervals problem?

  • @koteshmeesala1630
    @koteshmeesala1630 2 ปีที่แล้ว +2

    Is this necessary "res = max(res,count)". I think this will also work
    if start[s] < end[e]:
    count+=1
    else:
    e+=1
    return count

    • @subhashreebanik8131
      @subhashreebanik8131 2 ปีที่แล้ว

      Suppose there are 5 meetings. 2 of them are overlapping and 3 of them are overlapping. Your approach would give the answer as 5 whereas the actual answer is 3. So, you need to decrement the count.

    • @JasonHong-lg4fz
      @JasonHong-lg4fz 2 ปีที่แล้ว +1

      @@subhashreebanik8131 What if we always move the start pointer to the next?
      if start[s] < end[e]:
      count+=1
      else:
      e+=1
      s += 1
      return count

  • @dream11tatyabichoo92
    @dream11tatyabichoo92 3 หลายเดือนก่อน

    this is more readable while(i < length) {
    if(start[i] < end[j]) {
    ++ days;
    ++i;
    } else {
    ++j;
    ++i;
    }

    }

  • @mehulsolanki9435
    @mehulsolanki9435 2 ปีที่แล้ว +1

    Clear. Concise. Brilliant as always.

  • @guynameddan427
    @guynameddan427 2 ปีที่แล้ว +2

    Thank you so much! The drawing was SUPER helpful to understand.

  • @Gerald-iz7mv
    @Gerald-iz7mv 2 ปีที่แล้ว

    you can also insert all times of the intervals + a flag if its a start/end_time it into a min_heap and check have a counter around it?

  • @Allen-tu9eu
    @Allen-tu9eu 2 ปีที่แล้ว

    I understand this problem with your 2 min explain. what a god

  • @ajitsdeshpande
    @ajitsdeshpande 5 หลายเดือนก่อน

    @Neetcode - Would this below simple solution with O(1) space not work :
    intervals.sort(key = lambda x: x.start)
    if len(intervals) == 0:
    return 0
    cr = 1 # number of conference rooms
    for i in range(1,len(intervals)):
    if intervals[i],start < intervals[i-1].end:
    cr+=1
    return cr
    I checked above code for the 2 test cases given and it did work. Do you see any edge cases where it might return incorrect result ?

  • @kareemsalem7950
    @kareemsalem7950 2 ปีที่แล้ว

    This is great but I don't see any point in lowering the count since the highest result will always be the count that has not been reduced by 1? Maybe it's more comprehensive this way but you can just increment the result whenever the first condition is true and be good.

  • @ahmad3823
    @ahmad3823 3 ปีที่แล้ว +1

    some of your videos are simply brilliant!

  • @ameydhimte_c5956
    @ameydhimte_c5956 ปีที่แล้ว +1

    I was asked this question in salesforce internship interview recently. Wasn't able to solve it 😣

  • @Dysfunctional704
    @Dysfunctional704 2 ปีที่แล้ว +2

    Clear explanation!

  • @vishwaskhurana1217
    @vishwaskhurana1217 3 ปีที่แล้ว +2

    Thanks for lintcode ;)

  • @arkamukherjee457
    @arkamukherjee457 2 ปีที่แล้ว +2

    Out of curiosity, can't we sort, and try to count the number of overlapping intervals?

  • @brandonnoll5527
    @brandonnoll5527 3 ปีที่แล้ว +1

    This is the best solution. Thanks

  • @yutao1982
    @yutao1982 8 หลายเดือนก่อน

    Nice, clear now!

  • @AkimboFire
    @AkimboFire 3 ปีที่แล้ว +2

    Can someone explain the intuition behind sorting the end array?

    • @AI_For_Scientists
      @AI_For_Scientists 2 ปีที่แล้ว +4

      if you dont sort the ends you may keep hitting a lot of starts and ends that you are not accounting for. technically if you sort the starts and your largest end point comes first as in the video, you will have all your meeting open by the time you hit 30 which is wrong.

  • @meharikr
    @meharikr 2 ปีที่แล้ว

    really great explanation, you did a great job!

  • @ryanpark757
    @ryanpark757 2 ปีที่แล้ว

    I don't have leedcode premium, so I can't test this answer, but I think this works in O(nlogn) time for sorting and constant memory. I'm essentially incrementing room counts by 1 any time the next meeting start time is less than the last earliest meeting end time. Whenever I come across schedule conflict, I "bump" the meeting that ends later and keep the end time of the one that ends earlier and use that to compare other subsequent meeting times.
    I'd be curious if this is wrong or if this could actually be a better solution.
    def min_meeting_rooms(self, intervals: List[Interval]) -> int:
    # Write your code here
    if len(intervals)

    • @susheelgounder5333
      @susheelgounder5333 ปีที่แล้ว

      Wont work

    • @susheelgounder5333
      @susheelgounder5333 ปีที่แล้ว

      Case where 1st meeting whose end is less than 2nd overlap with 2nd. And 2nd overlap with 3rd here if you take min end then meeting 1s end will be considered and you wont get overlap when compared with 3rd

    • @sministro
      @sministro ปีที่แล้ว

      @@susheelgounder5333 I know you commented a month ago but would you be able to provide an input example? Since I came up with the same solution the original commenter wrote but I'm also not able to test since this is LC premium. Thanks!

    • @xionggu9859
      @xionggu9859 11 หลายเดือนก่อน

      Could anyone answer why this solution doesn't work?

  • @hacker3191000
    @hacker3191000 2 ปีที่แล้ว

    TREMENDOUS EXPLANATION!

  • @dream11tatyabichoo92
    @dream11tatyabichoo92 3 หลายเดือนก่อน

    how about we take in one array and take start as 1 and end as -1 like for this example array like - [ { 0,1}, { 5,1}, {10, -1}, {10, 1}, { 15, -1}, { 30, -1} ]

  • @veliea5160
    @veliea5160 ปีที่แล้ว +1

    can someone explain why we had to track `res, count` both?

    • @BrunaGoncalves-gx3ys
      @BrunaGoncalves-gx3ys ปีที่แล้ว

      It is because the time most rooms were occupied in the "whole time". And the count is about how many rooms are occupied in the moment

  • @oqant0424
    @oqant0424 7 หลายเดือนก่อน

    Thanks

  • @rathan235
    @rathan235 ปีที่แล้ว

    Great job

  • @gabchen3000
    @gabchen3000 ปีที่แล้ว

    wouldn't your solution get stuck in the while loop if start[s] == end[e]? I feel like it is missing a
    elif start[s] == end[e]:
    e += 1
    s+=1

    • @NehaYadav-YT
      @NehaYadav-YT 7 หลายเดือนก่อน

      This condition will be covered in the else part

  • @jugsma6676
    @jugsma6676 5 หลายเดือนก่อน

    Not sure if this works: (dont have premium leetcode)
    def minMeetingRooms(intervals: list[Interval]) -> int:
    intervals.sort(key=lambda x: x.start)
    res = 0
    for i in range(1, len(intervals)):
    prev = intervals[i-1]
    curr = intervals[i]
    if prev.end > curr.start:
    res += 1
    if prev.end > curr.end:
    intervals[i].end = prev.end
    return res

  • @TomerBenDavid
    @TomerBenDavid 3 ปีที่แล้ว

    Which software do you use for drawing please?

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +3

      Paint3D

  • @tonyz2203
    @tonyz2203 2 ปีที่แล้ว

    why do we need to update res on every iteration in the while loop?

  • @dorondavid4698
    @dorondavid4698 2 ปีที่แล้ว +1

    Could you use the same algorithm as the first Meeting Rooms, and just increase the count every time there's a conflict?

    • @SevereMalfunction7
      @SevereMalfunction7 2 ปีที่แล้ว

      How would you know to decrease the count?

    • @meowmaple
      @meowmaple 2 ปีที่แล้ว

      I don't think so, just tried that greedy approach and it didn't work

  • @asadyusuf6596
    @asadyusuf6596 2 ปีที่แล้ว

    You are awesome, Thank you so much!!!!!

  • @hangchen
    @hangchen 2 ปีที่แล้ว +3

    Everyone can code, but it's an art to figure out an elegant solution.

  • @beyzayildirim0
    @beyzayildirim0 2 ปีที่แล้ว +1

    Hey, I was wondering why you didnt include the edge case in your code as start[s]==end[e] then s and e +=1

    • @silvermoose2631
      @silvermoose2631 2 ปีที่แล้ว +3

      It's because the edge case is already accounted for in the else statement, which is basically saying the same thing as "if start[s] >= end[e]". In the case that the start and end values are equal to each other, only e is incremented (not s), because a meeting has to end before the other starts.

  • @edwardteach2
    @edwardteach2 2 ปีที่แล้ว +1

    U a God

  • @janjan_uary
    @janjan_uary 2 ปีที่แล้ว

    the vdo is very helpful, thanks a lot.

  • @gauravarora5888
    @gauravarora5888 2 ปีที่แล้ว

    minimum platforms required variation

  • @mingjuhe1514
    @mingjuhe1514 2 ปีที่แล้ว

    Great video

  • @anasali-et3lc
    @anasali-et3lc 2 ปีที่แล้ว

    Would someone point out what would be wrong with my solution? I implemented a stack solution. After I sort my intervals, I put the first end time in my stack and iterate through the intervals. If the current start I encounter is >= the stack top, I pop until the current start is greater than or equal to the top and push the current end in the stack. Otherwise I just push the end of the interval inside the stack.

    • @송둡
      @송둡 ปีที่แล้ว

      As the ending time is not sorted when just pushing on to the stack, this approach would give a bigger value than the actual required meeting rooms. Try out this example (4,9), (9,10), (4,17)

  • @jiaoliy2864
    @jiaoliy2864 2 ปีที่แล้ว

    very clear!

  • @tarekfathi2003
    @tarekfathi2003 2 ปีที่แล้ว

    HI , did you try this test case [[1,5],[8,9],[8,9]] . Accoring to your solution , I think it will return error. please try this test case and write comment for the result

  • @rohitbk7920
    @rohitbk7920 2 ปีที่แล้ว

    this problem is similar to merge intervals

  • @anythingcommon
    @anythingcommon 3 ปีที่แล้ว +1

    @NeetCode or anyone can you please explains in bit detail how it's( NlogN) as time complexity, getting a little difficult to understand as I'm new in python. is it for sorting time complex will be (NlogN) and loop 0(N), hence its (NlongN)?

    • @evilmorty9429
      @evilmorty9429 3 ปีที่แล้ว +1

      Yeah exactly !

    • @80kg
      @80kg 3 ปีที่แล้ว

      Yes the buildin sort is nlogn

    • @dorondavid4698
      @dorondavid4698 2 ปีที่แล้ว +1

      Sorting time is N Log N
      Going through the interval list is N
      That's N + N Log N, because you aren't going through the intervals at the SAME TIME AS the sorting (well you are during the sort, but you understand what I mean).
      So, you drop the N since you're looking for the biggest (almost worst) time, which is N LOG N.
      Anytime you do two operations together, they are multiplied, like a for loop inside another for loop. (M*N)
      If you have two for loops separate from each other, they are added (M+N)

    • @8Trails50
      @8Trails50 2 ปีที่แล้ว

      The short answer is because anytime you sort an array, the theoretical best time complexity for a comparison based sorting algorithm is NLogN. Since the rest of the code runs in linear time, the time complexity is dominated by the sorting - so we drop the time it takes to run through the intervals. Therefore, we say NLogN

  • @krishnapurohit3494
    @krishnapurohit3494 3 ปีที่แล้ว

    Can be solved in O(N) using difference array

    • @SreenathV
      @SreenathV 3 ปีที่แล้ว

      how? Without sorting?

    • @MistarKillar
      @MistarKillar 3 ปีที่แล้ว +1

      @@SreenathV Look into prefix sum algorithm

  • @alexanderp7521
    @alexanderp7521 20 วันที่ผ่านมา

    ```python
    class Solution:
    def __init__(self):
    self.res = 0
    def minMeetingRooms(self, intervals: List[Interval]) -> int:
    if not intervals: return 0
    intervals.sort(key=lambda x: x.end)
    ovs = self.overlaps(intervals)
    self.res += 1
    if len(ovs):
    self.minMeetingRooms(ovs)
    return self.res
    def overlaps(self, ints: List[Interval]) -> List[Interval]:
    prev = None
    res = []
    for item in ints:
    if prev is None or prev.end

  • @anik._.
    @anik._. 2 ปีที่แล้ว

    GE for Great Explanation

  • @anthonya880
    @anthonya880 ปีที่แล้ว

    any alternative to leetcde and lintcode ?
    Anyone please help.

  • @Marutesha
    @Marutesha 2 ปีที่แล้ว

    Python solution, easier to understand and remember
    class Solution(object):
    def minMeetingRooms(self, intervals):
    """
    :type intervals: List[List[int]]
    :rtype: int
    """
    sorted_intervals = []
    rooms = 0
    max_rooms = float("-inf")
    for i, each in enumerate(intervals, 1):
    sorted_intervals.append([each[0], 1, i])
    sorted_intervals.append([each[1], -1, i])
    sorted_intervals.sort()
    for start, time, event_id in sorted_intervals:
    if time != -1:
    rooms += 1
    max_rooms = max(rooms, max_rooms)
    else:
    rooms -= 1
    return max_rooms
    Python solution, easier to understand and remember

  • @phoenix_1_3
    @phoenix_1_3 ปีที่แล้ว

    This is Klee's Algorithm, right??

  • @RandomShowerThoughts
    @RandomShowerThoughts 2 หลายเดือนก่อน

    lol how would someone even build the intuition to think of something like this 🤣

  • @junhuang9047
    @junhuang9047 5 หลายเดือนก่อน

    Why does this algorithm work?

  • @harishsn4866
    @harishsn4866 2 ปีที่แล้ว

    Can anyone tell me why does it throw error when i use i.start and i.end in python. It says "list object has no attribute start".

    • @joyceawesome1705
      @joyceawesome1705 2 ปีที่แล้ว +4

      use start = sorted([i[0] for i in intervals]) and end = sorted([i[1] for i in intervals]). That should resolve the error.

    • @subhashreebanik8131
      @subhashreebanik8131 2 ปีที่แล้ว

      intervals is an object on Lintcode whereas it's a list on Leetcode

  • @Krankschwester
    @Krankschwester 5 หลายเดือนก่อน +1

    Sweep line!

  • @samsulalam7827
    @samsulalam7827 2 ปีที่แล้ว

    intervals = [(0,30),(5,10),(15,20)]
    intervals.sort(key = lambda i:i[0])
    res = 1
    prevEnd = intervals[0][1]
    for start, end in intervals[1:]:
    if start < prevEnd:
    res += 1
    prevEnd = min(end, prevEnd)
    else:
    prevEnd = min(end, prevEnd)
    print(res)
    Is it a valid solution for this problem? Just followed the similar technique of the problem "Non overlapping intervals". Link: th-cam.com/video/nONCGxWoUfM/w-d-xo.html

    • @jaredtewodros
      @jaredtewodros ปีที่แล้ว

      That's what I'm wondering as well. Just don't have LeetCode Premium to check. Did you try running this on LintCode?