LeetCode 56. Merge Intervals (Algorithm Explained)

Поделиться
HTML-код
  • Опубликовано: 19 окт 2024

Комментарии • 114

  • @adarshmishra4431
    @adarshmishra4431 2 года назад +37

    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 года назад +17

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

    • @cloud5887
      @cloud5887 4 года назад +1

      you mind to mention where that interview was?

    • @darrenwang7613
      @darrenwang7613 4 года назад +5

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

  • @felixrajkumar3177
    @felixrajkumar3177 3 года назад +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

  • @anoopm3605
    @anoopm3605 5 лет назад +10

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

  • @mangeshkumargabhane4671
    @mangeshkumargabhane4671 4 года назад +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 ??

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

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

  • @vikramchaudhary440
    @vikramchaudhary440 3 года назад +1

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

  • @jyothisejohny
    @jyothisejohny 2 года назад +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.

  • @pradip318
    @pradip318 3 года назад +1

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

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

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

  • @akashbharatwaj6945
    @akashbharatwaj6945 4 года назад +4

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

  • @purveeagrawal1933
    @purveeagrawal1933 Месяц назад

    Best explanation I have ever come across for this question🎉

  • @surajgrandhi6742
    @surajgrandhi6742 4 года назад

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

  • @parassaini9010
    @parassaini9010 2 года назад +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.

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

  • @aravindhsaairavichandran8404
    @aravindhsaairavichandran8404 4 года назад

    Long live Nick White.. thanks man

  • @sakshiaggarwal6199
    @sakshiaggarwal6199 Год назад

    Thank you so much Nick.
    God Bless Everyone😇

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

  • @nribackpacker
    @nribackpacker 3 года назад +1

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

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

  • @julietgeorge4858
    @julietgeorge4858 4 года назад

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

  • @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 4 года назад +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 3 года назад

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

  • @yassineattia3009
    @yassineattia3009 4 года назад +1

    Great stuff! love the authenticity in you

  • @prachisharma7500
    @prachisharma7500 2 года назад

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

  • @sidhartheleswarapu
    @sidhartheleswarapu 8 месяцев назад

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

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

  • @maksymr.7191
    @maksymr.7191 Год назад

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

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

  • @shusenacademy
    @shusenacademy 4 года назад

    can we use for loop with an index, for ( int i = 0 ; i < intervals.length; i++ ) ? 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 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 ??

  • @piyushgupta2325
    @piyushgupta2325 Год назад

    I don't get the comparator part

  • @HiBMlive
    @HiBMlive 5 лет назад

    Thanks. LC 76 video whenever you get time.

  • @adarshupadhyay8265
    @adarshupadhyay8265 3 года назад

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

  • @rodanm
    @rodanm 3 года назад +2

    0:06, best part of the video hahaha

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

  • @ihopethiscommentisntabusiv4670
    @ihopethiscommentisntabusiv4670 3 года назад

    Is there a linear solution?

  • @SHSelect
    @SHSelect 2 года назад +3

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

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

  • @renjieyu8700
    @renjieyu8700 3 года назад

    Very helpful,thank you dude!

  • @infinteuniverse
    @infinteuniverse 3 года назад +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?

  • @amitnain8489
    @amitnain8489 4 года назад +2

    great man. keep it up, 1 like from india

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

  • @sagargada73
    @sagargada73 4 года назад

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

  • @devyashb
    @devyashb 4 года назад

    the best explanation ever thanks man

  • @chelseaip759
    @chelseaip759 3 года назад

    What's the time complexity

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

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

  • @rohitparthasarathy6671
    @rohitparthasarathy6671 3 года назад

    Very well explained.

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

  • @manjushajagtap3718
    @manjushajagtap3718 4 года назад

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

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

  • @thechhavibansal
    @thechhavibansal 5 лет назад +1

    VERY HELPFUL! Thanks

  • @HarshGangwar
    @HarshGangwar 4 года назад +1

    Please explain Super Washing Machines of Leetcode.

  • @kose241
    @kose241 4 года назад

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

  • @anirbandey303
    @anirbandey303 4 года назад

    Great explanation. Thanks sir.

  • @dheerajkumark7165
    @dheerajkumark7165 3 года назад

    great explanation!!

  • @cryptojeff3993
    @cryptojeff3993 4 года назад

    Crystal clean. Thanks

  • @patagoniachief5973
    @patagoniachief5973 3 года назад

    big thank you from UB ;)

  • @piyushgupta2325
    @piyushgupta2325 Год назад

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

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

  • @farzanatasnim7339
    @farzanatasnim7339 2 года назад

    Thanks man!

  • @palak2708
    @palak2708 3 года назад

    wow, great solution.

  • @LUCIFER-lw4rc
    @LUCIFER-lw4rc 4 месяца назад +1

    10:12 💀

  • @venpro8705
    @venpro8705 4 года назад

    Can u slove hacker earth challenges

  • @ManpreetSingh-tf5ef
    @ManpreetSingh-tf5ef Год назад

    thanks

  • @doomhead9109
    @doomhead9109 2 года назад

    thank you sooooo much

  • @priyankareddy7408
    @priyankareddy7408 2 года назад

    Thank you! I got unstuck

  • @deluluvish
    @deluluvish 4 месяца назад

    thank u so much

  • @miteshkumar3183
    @miteshkumar3183 4 года назад

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

  • @Steklopod
    @Steklopod 6 месяцев назад

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

  • @akhilguptavibrantjava
    @akhilguptavibrantjava 4 года назад

    Awesome

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

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