LeetCode 56. Merge Intervals (Algorithm Explained)

Поділитися
Вставка
  • Опубліковано 9 січ 2025

КОМЕНТАРІ • 115

  • @adarshmishra4431
    @adarshmishra4431 2 роки тому +42

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

  • @xnl3358
    @xnl3358 5 років тому +51

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

  • @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

  • @darrenwang7613
    @darrenwang7613 4 роки тому +16

    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!

  • @shubhamchourasia2265
    @shubhamchourasia2265 3 роки тому +5

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

  • @mangeshkumargabhane4671
    @mangeshkumargabhane4671 5 років тому +5

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

  • @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 ??

  • @anoopm3605
    @anoopm3605 5 років тому +10

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

  • @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

  • @pradip318
    @pradip318 3 роки тому +1

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

  • @purveeagrawal1933
    @purveeagrawal1933 4 місяці тому +1

    Best explanation I have ever come across for this question🎉

  • @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.

  • @jyothisejohny
    @jyothisejohny 3 роки тому +4

    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 роки тому +2

      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.

  • @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

  • @vikramchaudhary440
    @vikramchaudhary440 3 роки тому +1

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

  • @surajgrandhi6742
    @surajgrandhi6742 4 роки тому

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

  • @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.

  • @hacker-7214
    @hacker-7214 5 років тому

    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.

  • @akashrAnD
    @akashrAnD 4 роки тому +4

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

  • @nribackpacker
    @nribackpacker 4 роки тому +1

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

  • @parassaini9010
    @parassaini9010 3 роки тому +1

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

  • @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.

  • @sakshiaggarwal6199
    @sakshiaggarwal6199 2 роки тому

    Thank you so much Nick.
    God Bless Everyone😇

  • @stith_pragya
    @stith_pragya Рік тому +1

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

  • @jamjam3448
    @jamjam3448 2 роки тому +1

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

  • @yassineattia3009
    @yassineattia3009 4 роки тому +1

    Great stuff! love the authenticity in you

  • @julietgeorge4858
    @julietgeorge4858 4 роки тому

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

  • @aravindhsaairavichandran8404
    @aravindhsaairavichandran8404 4 роки тому

    Long live Nick White.. thanks man

  • @maksymr.7191
    @maksymr.7191 2 роки тому

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

  • @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.

  • @sabreenkaur7349
    @sabreenkaur7349 4 роки тому

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

  • @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 🙂

  • @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 3 роки тому

      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 ??

  • @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)

  • @rodanm
    @rodanm 4 роки тому +2

    0:06, best part of the video hahaha

  • @prachisharma7500
    @prachisharma7500 2 роки тому

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

  • @瑞莹吴
    @瑞莹吴 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?

  • @ShusenAcademy
    @ShusenAcademy 4 роки тому

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

  • @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?

  • @renjieyu8700
    @renjieyu8700 3 роки тому

    Very helpful,thank you dude!

  • @amitnain8489
    @amitnain8489 4 роки тому +2

    great man. keep it up, 1 like from india

  • @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

  • @OrphanedZombie
    @OrphanedZombie 11 місяців тому

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

  • @devyashb
    @devyashb 5 років тому

    the best explanation ever thanks man

  • @HiBMlive
    @HiBMlive 5 років тому

    Thanks. LC 76 video whenever you get time.

  • @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.

  • @divergenny
    @divergenny День тому

    Thank you very much Nick

  • @sagargada73
    @sagargada73 4 роки тому

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

  • @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.

  • @yuchenguo9108
    @yuchenguo9108 4 роки тому

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

  • @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[ ][ ]

  • @manjushajagtap3718
    @manjushajagtap3718 4 роки тому

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

  • @adarshupadhyay8265
    @adarshupadhyay8265 3 роки тому

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

  • @ihopethiscommentisntabusiv4670
    @ihopethiscommentisntabusiv4670 3 роки тому

    Is there a linear solution?

  • @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

  • @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]

  • @rohitparthasarathy6671
    @rohitparthasarathy6671 3 роки тому

    Very well explained.

  • @chelseaip759
    @chelseaip759 4 роки тому

    What's the time complexity

  • @dheerajkumark7165
    @dheerajkumark7165 3 роки тому

    great explanation!!

  • @anirbandey303
    @anirbandey303 4 роки тому

    Great explanation. Thanks sir.

  • @patagoniachief5973
    @patagoniachief5973 4 роки тому

    big thank you from UB ;)

  • @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.

  • @LUCIFER-lw4rc
    @LUCIFER-lw4rc 6 місяців тому +1

    10:12 💀

  • @thechhavibansal
    @thechhavibansal 5 років тому +1

    VERY HELPFUL! Thanks

    • @NickWhite
      @NickWhite  5 років тому

      Thanks for watching!

  • @piyushgupta2325
    @piyushgupta2325 Рік тому

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

  • @piyushgupta2325
    @piyushgupta2325 Рік тому

    I don't get the comparator part

  • @cryptojeff3993
    @cryptojeff3993 4 роки тому

    Crystal clean. Thanks

  • @SHSelect
    @SHSelect 2 роки тому +3

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

  • @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

  • @HarshGangwar
    @HarshGangwar 4 роки тому +1

    Please explain Super Washing Machines of Leetcode.

  • @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) ....

  • @kose241
    @kose241 4 роки тому

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

  • @palak2708
    @palak2708 3 роки тому

    wow, great solution.

  • @farzanatasnim7339
    @farzanatasnim7339 2 роки тому

    Thanks man!

  • @venpro8705
    @venpro8705 4 роки тому

    Can u slove hacker earth challenges

  • @priyankareddy7408
    @priyankareddy7408 2 роки тому

    Thank you! I got unstuck

  • @doomhead9109
    @doomhead9109 2 роки тому

    thank you sooooo much

  • @miteshkumar3183
    @miteshkumar3183 4 роки тому

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

  • @ManpreetSingh-tf5ef
    @ManpreetSingh-tf5ef Рік тому

    thanks

  • @deluluvish
    @deluluvish 7 місяців тому

    thank u so much

  • @Steklopod
    @Steklopod 8 місяців тому

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

  • @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

  • @akhilguptavibrantjava
    @akhilguptavibrantjava 5 років тому

    Awesome

  • @andychang1179
    @andychang1179 4 роки тому

    Thanxxxxxx

  • @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.