LeetCode 56. Merge Intervals (Algorithm Explained)

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

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

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

    there's not many java creators out there ..you are doing a great job dude ..keep going

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

    9:16 - "Literally" took me 1 hour to understand from a code from Leetcode.

  • @xnl3358
    @xnl3358 5 ปีที่แล้ว +51

    man.. this is crazy, I was stuck in this question today, and you came up with best explanation

  • @darrenwang7613
    @darrenwang7613 4 ปีที่แล้ว +17

    just finished an interview where this was the question, damn. Wish I saw this sooner... keep doing your thing Nick!

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

      you mind to mention where that interview was?

    • @darrenwang7613
      @darrenwang7613 4 ปีที่แล้ว +5

      @@cloud15487 Kargo, a smaller tech company. This is a good interview question though so could show up at any company.

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

    It makes sense once you realize updating the last index of current_interval (line 20), also updates it in the ArrayList. Thanks so much for this!

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

    I’m stuck on something. How does current_interval[1] = Math.max(current_end, next_end) in the loop cause a change in the arrayList? If it is because we pass by reference then why was there not change in current_interval in the array list when we did current_interval = interval?

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

      So, current_interval is pointing to the first element of output_arr when "current_interval[1] = Math.max(current_end, next_end)" is done. So, it changes the end point of the first array. But current_interval changes to point to the new interval when "current_interval = interval" is done. So, current_interval acts as just the pointer for the different arrays in the list at different points. But the actual arrays in the list remain the same. This is because list is not stored contiguously but it is just a chain of elements pointing to the next one.

    • @Will-en6gw
      @Will-en6gw 2 ปีที่แล้ว

      Yeah I was stuck on this too but what Prakansh said makes sense, current_interval is pointing to the first element in the output list because we just got done adding it. Then when doing current_interval[1] = Math.max(current_end, next_end) we are directly accessing a primitive data type, which we can directly mutate. This is why it gets changed in the output list, because it is a primitive data type. Then when we do current_interval = interval, we are telling the compiler to point to interval because arrays are reference data types, not primitives.

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

    6:32 I am a little confused because you just initialized an int as an int* and there was no error, i mean intervals was a 2d array... One of which array was containing only pointers and you initialized that pointer to an int ??

  • @ianchui
    @ianchui 5 ปีที่แล้ว +14

    I'm so glad I found your channel, very helpful to watch. I always add your videos to my watch later, then just watch when I'm on the bus

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

    In which step are we updating the (second no of interval). after encountering an overlap, we do find largest of two curr_end and next_end, but before only we added it to output_arr. so we do need to update [1, 3] to [1, 6]. Where are we doing that.

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

    I have a doubt here . After storing the 1st interval in "current_interval", which is ([1, 3]) in this case, you start iterating through the intervals . When you do that it should always start from the 1st interval ([1, 3]). Then how's it pointing to the 2nd interval ([2, 6]) during the 1st iteration? It's like comparing the same element with itself .Can someone explain ?

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

      I was stuck on too but if you merge [1,3] with [1,3] you get [1,3] since the Math.max(current_end, next_end) is basically Math.max(3,3). So first iteration compares itself and creates a clone.

  • @felixrajkumar3177
    @felixrajkumar3177 4 ปีที่แล้ว +6

    You can improve the run time if the you use arr1[0] - arr2[0] instead of compare while sorting. BTW the explanation was great

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

    what if we do boom boom boom in interview just like u did @7:33

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

    Hi Nick.. Can you make a video on "How the Comparator does the sorting stuffs internally" ??

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

    1. if(intervals.lengtharr1[0]-arr2[0]);
    5 List l =new ArrayList();
    6 int[] current;
    7 current = intervals[0];
    8 l.add(current);
    9 for(int[] interval:intervals){

    10 int cbegin = current[0];
    11 int cend = current[1];
    12 int nbegin = interval[0];
    13 int nend = interval[1];
    14 if(cend>=nbegin){
    15 current[1] = Math.max(cend,nend);
    16 }
    17 else{
    18 current = interval;

    19 l.add(current);
    20 }
    21 }
    return l.toArray(new int[l.size()][]);
    Could u pls xplain line no 18 current is pass by reference ,changes is done automatically to list,but at line 18 current=interval ,so previous current in list is *LOST*,because list stores reference of current

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

    Best explanation I have ever come across for this question🎉

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

    how are you updating list with the current intervals end directly
    can you pleas explain it in detail please ??

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

      I think he is not copying the array, he is setting a reference to it, so I guess that makes it possible to directly change the value in the arraylist, in the else statement it looks like he changes the reference and cuts off that connection

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

      So he's able to do that because ArrayList is mutable in Java. Whatever modification he performs on the current interval within the for loop is also reflected inside the interval found in output_arr. If he were to update the interval under a new variable assignment, then the interval update wouldn't roll over to the interval found in output_arr. This same reasoning is also applicable to Python.

  • @hacker-7214
    @hacker-7214 4 ปีที่แล้ว

    The idea u take the current interval initially and add it into the list is genius and updating it. Like eventho for loops r easy. I find it hard to even code loops cuz u want the same thing to happen in loops but i always mess up.

    • @hacker-7214
      @hacker-7214 4 ปีที่แล้ว

      @@bilaltariq7819 thank you youre a genius! Enevn tho this concept seems obvious idk why i didnt see the importance of it. I need to practice finding out the loop invariant everytime i encounter a problem that requires a loop.

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

    Just a question if anyone could tell: current_interval=interval[0] and when we iterate : for(int[ ] interval : intervals) so where does it starts from .................interval=intervals[0] ? is it so if it is so, we check same elements both pointing to intervals[0] ? thanks . PLease help !!!

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

      That's correct, we check the first element by itself change it to the same element going in the if condition and not really adding it again.
      We could have just used a for loop starting from the index 1 instead, that would have been a bit more clear.

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

      @@nishantsabharwal13 thanks 🙂

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

    Is there a faster way to do this? I got a bad runtime score.

  • @瑞莹吴
    @瑞莹吴 2 ปีที่แล้ว

    According to example 1, this statement
    int[] cur_interval=intervals[0];
    output_arr.add(cur_interval);
    has put [1,3] into the answer array.
    Aren't you wrong?

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

    Whats the time and space complexity :-O(n) ?

  • @anoopm3605
    @anoopm3605 5 ปีที่แล้ว +10

    Thanks Nick. This was very helpful.Please do similar popular quesitions

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

    I got a method which is faster but uses a little more memory. What I did was initialize two variables called which are set as intervals[0][0] and intervals[0][1].
    Then I make a third variable in a for loop which is set to intervals[i][0] which compares its value to the upper interval, if its lower, the upper interval is modified if interval[i][1] is higher than the current upper interval. If intervals[i][0] is higher than the lower and upper bound are pushed to a 2nd array and new bounds, intervals[i][0] (lower) and intervals[i][1] (higher) are created.
    Keep doing this until the for loop ends after which we push the final values of "c_val" and "bound" as an array to our 2nd vector and return that vector. You'll need to sort intervals first before assigning the variables.

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

    Thanks Nick! V helpful :)
    Can someone help me understand how come if I change any value of current_interval, then it automatically updates in the output_arr list? Is it because of pass by reference nature of Java?

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

      well, this is exactly what I'm confused with too ... could you understand it?

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

      exactly same doubt. found ans?

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

      Guys found the answer ??

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

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

  • @sabreenkaur7349
    @sabreenkaur7349 4 ปีที่แล้ว

    What is the time and space complexity of your solution in the video?

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

    More power to you,I would request everyone to support this guy.

  • @jerrywu751
    @jerrywu751 4 ปีที่แล้ว

    what if when the for loop runs into the last interval the (current_end > next_begin) is True and therefore it doesn't put the current array into the output_arr?

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

    How is modifying the current_interval[1] modifying the value in the output_arr . Sorry if it is a stupid question , learning DS from the start

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

      I have the same question .

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

      ArrayLists are mutable in java, That means you can change the value at any point of time, So he just goes ahead and updates the value and it reflects in the output array too.

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

    Would this work with straddling intervals?
    E.g. [3,4], [1,5]

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

      Yeah it will, that's why he sorted the array in the first place. If the intervals are sorted based on their first indexes, we can easily merge them using this algo.

    • @daniellee9825
      @daniellee9825 4 ปีที่แล้ว

      he sorts the array by first element and then he uses Math.max(..) to choose 5 instead of 4 (in your example)

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

    I spent a few hours yesterday night and solved it by myself

  • @shusenacademy
    @shusenacademy 4 ปีที่แล้ว

    can we use for loop with an index, for ( int i = 0 ; i < intervals.length; i++ ) ? thanks

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

    You are amazing brother, your coding style and explanation is pretty simple.

  • @surajgrandhi6742
    @surajgrandhi6742 4 ปีที่แล้ว

    I think the best explanation u have ever given in your videos
    may be i had understood in first attempt

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

    unable to understand return output_arr.toArray(new int[output_arr.size()][]);

  • @mangeshkumargabhane4671
    @mangeshkumargabhane4671 4 ปีที่แล้ว +5

    I'm so glad I found your channel, very helpful to watch.

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

    Is there a linear solution?

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

    0:06, best part of the video hahaha

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

    I don't get the comparator part

  • @chelseaip759
    @chelseaip759 4 ปีที่แล้ว

    What's the time complexity

  • @razorhxh7371
    @razorhxh7371 4 ปีที่แล้ว

    can someone explain why in the return statement the array is left blank. new int[output_arr.sizeOf()] [ ])l

    • @devanshikhare1342
      @devanshikhare1342 4 ปีที่แล้ว

      I think second [ ] is for collumn as return type is int[ ][ ]

  • @sagargada73
    @sagargada73 4 ปีที่แล้ว

    what does (arr1,arr2) -> Integer.compare(arr[0],arr[1]); do

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

    Thank you, I was totally stuck even didn't understand the question but u helped me nice explanation.

  • @nikhilv6
    @nikhilv6 4 ปีที่แล้ว

    Was asked similar problem in Uber 1st round, this is like OR one more was AND the intervals of 2 2D arrays

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

    I hate when he says "ITS A PRETTY EASY PROBLEM"

  • @LUCIFER-lw4rc
    @LUCIFER-lw4rc 6 หลายเดือนก่อน +1

    10:12 💀

  • @jugsma6676
    @jugsma6676 4 ปีที่แล้ว

    Wouldn't this be the easiest way to do?
    def merge_itervals(intervals):
    last_interval_val = intervals[0][0]-1
    for i, interval in enumerate(intervals):
    if interval[0]

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

    Great stuff! love the authenticity in you

  • @aravindhsaairavichandran8404
    @aravindhsaairavichandran8404 4 ปีที่แล้ว

    Long live Nick White.. thanks man

  • @yuchenguo9108
    @yuchenguo9108 4 ปีที่แล้ว

    Hey Nick, can you do a video on 986. Interval List Intersections?

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

    Who comes up with these answers in 45 min during a coding assessment from only seeing this the first time?? I just finished a similar question 'insert intervals.' It took me so long to do, but I did it without looking for help. It feels like I'll never pass those coding interviews.

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

    Thank you so much Nick.
    God Bless Everyone😇

  • @julietgeorge4858
    @julietgeorge4858 4 ปีที่แล้ว

    Thank you, I am coding in javascript and this helped.

  • @HiBMlive
    @HiBMlive 5 ปีที่แล้ว

    Thanks. LC 76 video whenever you get time.

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

    Why can't we simply do this instead (python):
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:

    if len(intervals) = intervals[i][0]:
    result[count][1] = max(intervals[i][1], result[count][1])
    else:
    result.append(intervals[i])
    count += 1
    return result

  • @Vishal-ki2df
    @Vishal-ki2df 4 ปีที่แล้ว

    What does this ' -->' mean?

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

      it refers to the lambdas .. snippet example : int compare(Int h1, Int h2) {
      return h1.compareTo(h2);
      } is replaced here as (h1,h2)--> h.compareTo(h2) ....

  • @mananpatel884
    @mananpatel884 4 ปีที่แล้ว

    # python
    intervals = [[1,3],[6,9]]
    newInterval = [2,5]
    intervals.append(newInterval)
    intervals.sort()
    final_list = []
    current_interval = intervals[0]
    # print current_interval[0]
    final_list.append(current_interval)
    for interval in intervals:
    current_begin = current_interval[0]
    current_end = current_interval[1]
    next_begin = interval[0]
    next_end = interval[1]
    if current_end >= next_begin:
    current_interval[1] = max(current_end,next_end)
    else:
    current_interval = interval
    final_list.append(current_interval)
    print final_list

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

    Very helpful,thank you dude!

  • @manjushajagtap3718
    @manjushajagtap3718 4 ปีที่แล้ว

    This is really great explanation. Can you please explain the complexity also. It will be of great help.

    • @Harsh-di5rl
      @Harsh-di5rl 2 ปีที่แล้ว

      T.C : NlogN + N
      S.C : N

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

    Very well explained.

  • @maksymr.7191
    @maksymr.7191 2 ปีที่แล้ว

    Thank you, my friend. I appreciate your work very much. Keep it up! God bless you.

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

    I WAS SO FUCKING CONFUSED BRO I THOUGHT WHY WAS HE OPERATING IN THE 2D ARRAY OMG

  • @kose241
    @kose241 4 ปีที่แล้ว

    Do you normally redo the entire video if you mess up?

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

    Please explain Super Washing Machines of Leetcode.

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

    This way of coding might help you clear the interviews, but is highly discouraged in practice since the leaky side effects are impossible to track in enterprise level projects.

  • @venpro8705
    @venpro8705 4 ปีที่แล้ว

    Can u slove hacker earth challenges

  • @devyashb
    @devyashb 4 ปีที่แล้ว

    the best explanation ever thanks man

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

    great explanation!!

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

    great man. keep it up, 1 like from india

  • @anirbandey303
    @anirbandey303 4 ปีที่แล้ว

    Great explanation. Thanks sir.

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

    Thank you! I got unstuck

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

    big thank you from UB ;)

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

    VERY HELPFUL! Thanks

    • @NickWhite
      @NickWhite  5 ปีที่แล้ว

      Thanks for watching!

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

    Thanks man!

  • @cryptojeff3993
    @cryptojeff3993 4 ปีที่แล้ว

    Crystal clean. Thanks

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

    wow, great solution.

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

    Learn case convention in Java first. Then got to algos :-)

  • @ManpreetSingh-tf5ef
    @ManpreetSingh-tf5ef ปีที่แล้ว

    thanks

  • @miteshkumar3183
    @miteshkumar3183 4 ปีที่แล้ว

    You should have showed how to do this with interval trees. The sorting method is trivial.

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

    thank you sooooo much

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

    thank u so much

  • @codedoctor3265
    @codedoctor3265 4 ปีที่แล้ว

    class Solution:
    def merge(self, intervals):
    intervals.sort(key=lambda x: x[0])
    merged = []
    for interval in intervals:
    # if the list of merged intervals is empty or if the current
    # interval does not overlap with the previous, simply append it.
    if not merged or merged[-1][1] < interval[0]:
    merged.append(interval)
    else:
    # otherwise, there is overlap, so we merge the current and previous
    # intervals.
    merged[-1][1] = max(merged[-1][1], interval[1])
    return merged

  • @andychang1179
    @andychang1179 4 ปีที่แล้ว

    Thanxxxxxx

  • @akhilguptavibrantjava
    @akhilguptavibrantjava 5 ปีที่แล้ว

    Awesome

  • @sebastianbaptiste4905
    @sebastianbaptiste4905 4 ปีที่แล้ว

    dude

  • @TheJuancar0000
    @TheJuancar0000 4 ปีที่แล้ว

    I came here looking for a linear solution :(

  • @karana2260
    @karana2260 4 ปีที่แล้ว

    I'm so glad I found your channel, very helpful to watch.