Merge Intervals - Sorting - Leetcode 56

  Рет қаралды 169,165

NeetCode

NeetCode

Күн бұрын

Пікірлер: 91
@vishnuv.7807
@vishnuv.7807 3 жыл бұрын
I just started the LeetCode grind and this was my first medium problem I had attempted. Your explanation was crazy clear and it really helped me learn how this algorithm works.
@NeetCode
@NeetCode 3 жыл бұрын
I'm happy it was helpful 🙂
@II_superluminal_II
@II_superluminal_II Жыл бұрын
man out of all the other over zealous ones, you are one of the most humble and creative teacher I have met. I hope you know you are helping alot of people who are good coders not confident with interviewing help ease a little tension.
@srinadhp
@srinadhp 3 жыл бұрын
Thank you so much! I complicated the solution way too much.. but when I look at yours, I now understand what I missed. Your explanation as usual, helped a great deal. Thank you so much!
@licokr
@licokr 10 ай бұрын
Thank you ver ymuch, NeetCode. Not only drawing, your explanation and code is very straight-forward and easy understand. I'm really glad I found out your channel!
@hwang1607
@hwang1607 Жыл бұрын
just using intervals = sorted(intervals) works as well
@ShivamSharma-t8c
@ShivamSharma-t8c Күн бұрын
affects space complexity as it creates new object, but good option for a beginner tho
@yilinliu2238
@yilinliu2238 3 жыл бұрын
thank god whenever you have a video on the lc I am doing
@t-distributedkid3825
@t-distributedkid3825 2 жыл бұрын
This is my first medium problem like many others Explanation was great... On point
@dominic_lee
@dominic_lee 2 жыл бұрын
this is a really good problem。it is a bit tricky but you can learn a lot
@rahulshah6119
@rahulshah6119 4 жыл бұрын
great video again! btw you don't need a custom lambda key comparator, python sorts by the first element by default anyways so `intervals.sort()` would work as well for line 4.
@husainshaikh1433
@husainshaikh1433 3 жыл бұрын
Explicit is better than implicit
@marcelofernandes3230
@marcelofernandes3230 2 жыл бұрын
@@husainshaikh1433 Yeah, but I mean this is a feature of the language one should be aware for these interview questions. It's really useful for defining tiebreakers in heaps, for instance.
@neon13x
@neon13x Ай бұрын
If the first element is same python will compare the second element and so on, by passing a key function it will not check the rest of the values if key is same.
@cathyhuang8557
@cathyhuang8557 4 жыл бұрын
Good explanation~ Do you have a patreon? I would like to buy you a coffee to support your hard work! Keep working!
@NeetCode
@NeetCode 4 жыл бұрын
Thank you, that means a lot! If you would like to support on patreon here is the link: www.patreon.com/NEETcode (completely optional, teaching is already rewarding for me =) )
@nuamaaniqbal6373
@nuamaaniqbal6373 2 жыл бұрын
Your solutions are very intuitive and clean!
@KrishnaKumar-jz7zu
@KrishnaKumar-jz7zu 3 ай бұрын
Thank you very much, your way of approching problem and explanation makes difficult level problem easy for me !
@Sportamrina
@Sportamrina 5 күн бұрын
Thanks!
@NeetCode
@NeetCode 3 күн бұрын
Thank you so much!
@snake1625b
@snake1625b 3 жыл бұрын
The only video that helped me with this question. Thanks
@Cruzylife
@Cruzylife 2 жыл бұрын
gonna continue on this problem tomorrow. Your explanations are better than grokking's. Using your videos and Grokking is the ultimate combination that is helping me so much rn
@PippyPappyPatterson
@PippyPappyPatterson 2 жыл бұрын
Can you post a link to Grokking's channel? I searched "Grokking merge intervals" but didn't find anything. Or is it in a different medium?
@franklinmaradiaga2401
@franklinmaradiaga2401 2 жыл бұрын
@@PippyPappyPatterson I think CruzyLife was referring to Grokking the Coding Interview, which is a course to learn patterns for technical interviews
@PippyPappyPatterson
@PippyPappyPatterson 2 жыл бұрын
@@franklinmaradiaga2401 Thanks
@shantanukumar4081
@shantanukumar4081 2 жыл бұрын
You made it easy. Great Explanation !!!
@pa114able
@pa114able 3 жыл бұрын
Great explanation buddy! I was looking for implementation in Python and you described it perfectly!
@jackieli1724
@jackieli1724 Жыл бұрын
thank u very much😭the best leetcode video in youtube!
@ishxnnn
@ishxnnn Жыл бұрын
I love you Neetcode, you're my leetcode buddy
@adolfoestebanfragosomagall7975
@adolfoestebanfragosomagall7975 2 жыл бұрын
Great explanation, thank you!. It would be a good idea to also explain the O(n2) solution using connected components and then derive the optimal solution.
@DeGoya
@DeGoya 2 жыл бұрын
I actually had the idea of sorting them first, but I though there must be a better solution, since that would be too easy
@anshitasaxena3992
@anshitasaxena3992 7 ай бұрын
I wrote this way: def merge(self, intervals: List[List[int]]) -> List[List[int]]: i = 0 finalList = [] intervals.sort(key = lambda i: i[0]) while i < len(intervals): start = intervals[i][0] end = intervals[i][-1] while i+1 < len(intervals) and end >= intervals[i+1][0]: i+=1 end = max(end, intervals[i][-1]) finalList.append([start, end]) i += 1 return finalList
@zarynooi5669
@zarynooi5669 3 жыл бұрын
you are a life saver
@radelfalcao9327
@radelfalcao9327 2 жыл бұрын
very clear explanation
@ruiliang6819
@ruiliang6819 16 күн бұрын
Good vid, keep the good work up!
@kma1138
@kma1138 2 жыл бұрын
Learning python + leetcoding is sick
@aniruddhmukeshiiitdharwad7596
@aniruddhmukeshiiitdharwad7596 Жыл бұрын
love your channel man !! youre doing lovely work ! love from india!
@anonymoussloth6687
@anonymoussloth6687 2 жыл бұрын
Sometimes, we have to sort the intervals based on the end time like in activity selection problem. So when do we choose which?
@josecabrera7947
@josecabrera7947 2 жыл бұрын
Dude you are the best !!! I honestly attribute my near mastery of python and ability to solve leetcodes to you hahah. Youve taught me so much bro and for that i want to say thank you (:
@NeetCode
@NeetCode 2 жыл бұрын
Glad I could be helpful 🙂
@JamesBond-mq7pd
@JamesBond-mq7pd Жыл бұрын
super efficient way. impressive. unreal. wow.
@sun-ship
@sun-ship 11 ай бұрын
thank you so much for your work!!
@douglaswong6560
@douglaswong6560 2 жыл бұрын
clean and concise, thank you!
@venkateshv626
@venkateshv626 Жыл бұрын
Very nice explanation
@harikuduva
@harikuduva 3 жыл бұрын
Can you answer the follow up of doing it from a stream opposed to a list?
@asdfasyakitori8514
@asdfasyakitori8514 Жыл бұрын
Great video!
@yashpathak9285
@yashpathak9285 3 жыл бұрын
Sometimes coding in Python feels like cheating!!
@mariambhatti8515
@mariambhatti8515 2 жыл бұрын
This guy must be given a nobel prize by leetcode :)
@jackfilleyreviews4030
@jackfilleyreviews4030 4 жыл бұрын
brooo i love you
@littlelittlebing
@littlelittlebing Жыл бұрын
if the interval length is 1, is interval [1:] out of index?
@YN-jz2kp
@YN-jz2kp 2 жыл бұрын
Nicely explained
@nathamuni9435
@nathamuni9435 2 жыл бұрын
One small qustion that since we sort the end ...why cant we pick the next value which will definitely be grater⁉❔
@raishamonga4364
@raishamonga4364 2 жыл бұрын
we only sorted from the start values, not from the ending values so for all we know the ending value of the next interval could actually be smaller than the ending value of the current interval. [1,23], [5,18] => the intervals are sorted form index 0 (or the starting value) and must be merged but if we merge them and make the merged interval [1,18] we just made the interval smaller so our final output would not be right
@jyotioh3723
@jyotioh3723 2 жыл бұрын
sorta hilarious how elegant these solutions look compared to what I tried to cook up looking at the problem =[
@xx133
@xx133 11 ай бұрын
Can’t this be done in place by using range instead?
@yogeshk8323
@yogeshk8323 Жыл бұрын
how you are handling empty list here
@ilanaizelman3993
@ilanaizelman3993 3 жыл бұрын
Amazing. Thx!
@TheStefanV
@TheStefanV 2 жыл бұрын
public int[][] merge(int[][] intervals) { Arrays.sort(intervals,(a,b)->a[0]-b[0]); List mergedIntervals = new ArrayList(); int[] current = intervals[0]; int[] next = new int[2]; for (int i = 0; i < intervals.length; i++) { next = i < intervals.length -1 ? intervals[i+1] : next; // pointer has reached end, cannot have a 'next' array if ( current[1] >= next[0] && i < intervals.length - 1) { // currentHi > nextLo // currentHi is now the max of currentHi and nextHi, continue onto next iteration and keep trying to merge more current[1] = Math.max(next[1], current[1]); } else { mergedIntervals.add(current); // cannot merge an interval, must add interval as is current = next; } } return mergedIntervals.toArray(new int[0][]); // convert to array }
@seenumadhavan4451
@seenumadhavan4451 Жыл бұрын
Learn python 😂
@דניאלאביב-ו6ת
@דניאלאביב-ו6ת 2 ай бұрын
why sorting by start is working, and by end isn't?
@joyceawesome1705
@joyceawesome1705 2 жыл бұрын
Great explanation and very simplified solution. I tried out the code and it failed on this test case: [[1,4],[0,4]]. The output is supposed to be [0, 4], instead I got [1, 4]
@joyceawesome1705
@joyceawesome1705 2 жыл бұрын
Nevermind. I found that my error came from initializing the output array before sorting the intervals.Thanks so much for this video.
@ruspatel1996
@ruspatel1996 2 жыл бұрын
Isn't using a slice instead of range slower?
@chair_smesh
@chair_smesh 2 жыл бұрын
It creates extra memory right?
@ruspatel1996
@ruspatel1996 2 жыл бұрын
@@chair_smesh Yes specifically O(k) space and it also takes O(k) time to copy the elements.
@sundararamanp
@sundararamanp 2 жыл бұрын
i always have the doubt. is it okay to use ready made functions like sort and lambda in ds algo interview round
@bharanidharan.m4245
@bharanidharan.m4245 2 жыл бұрын
Yes, because there is limited time to deal a problem and sorting is basic to everyone
@whonayem01
@whonayem01 2 жыл бұрын
Thanks
@qingyachen1635
@qingyachen1635 2 жыл бұрын
Great!!!
@Historyiswatching
@Historyiswatching 2 жыл бұрын
Gah I feel so dumb, these medium problems are hard. Maybe I should stick with easy ones ... if mediums are too hard? Right?
@manojk1494
@manojk1494 Жыл бұрын
Could anyone please help me on this...? def merge(intervals: List[List[int]]) -> List[List[int]]: ~~~~^^^^^ TypeError: list indices must be integers or slices, not type Process finished with exit code 1
@thecustompropper1279
@thecustompropper1279 2 жыл бұрын
what if one of the intervals completely lie inside another interval
@rickhouseshorts
@rickhouseshorts 2 жыл бұрын
I tweaked the algorithm by starting with a blank list for output and using a while i < sortedList.size and running DFS on each interval -> getAllValuesWithinRange(newInterval, previousInterval, index), then recursing and updating index (index + 1) IF currentStartingPoint
@dingus2332
@dingus2332 Жыл бұрын
Basically you took a minHeap and Stack to solve this
@johnwick2018
@johnwick2018 2 жыл бұрын
My solution: probably O(n^2) I have no idea how it works but here it is, after 4 hours and 12 attempts import numpy as np from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: n = max(intervals, key=lambda x: x[1])[1] temp = np.zeros(n + 1, np.uint8) for l, r in intervals: if l < r: if (temp[l] == 0 or temp[l] == 3) and (temp[r] == 0 or temp[r] == 3): temp[l] = 2 temp[r] = 2 temp[l + 1: r] = 1 elif temp[l] == 2 and temp[r] == 2: if np.count_nonzero(temp[:l + 1] == 2) & 1: temp[l] = 2 else: temp[l] = 1 if np.count_nonzero(temp[r:] == 2) & 1: temp[r] = 2 else: temp[r] = 1 temp[l + 1: r] = 1 elif temp[l] == 2 and temp[r] == 1: if np.count_nonzero(temp[:l + 1] == 2) & 1: temp[l] = 2 else: temp[l] = 1 temp[l + 1: r] = 1 elif temp[l] == 2 and (temp[r] == 0 or temp[r] == 3): temp[r] = 2 if np.count_nonzero(temp[: l + 1] == 2) & 1: temp[l] = 2 else: temp[l] = 1 temp[l + 1: r] = 1 elif (temp[l] == 0 or temp[l] == 3) and temp[r] == 2: temp[l] = 2 if np.count_nonzero(temp[r: n + 1] == 2) & 1: temp[r] = 2 else: temp[r] = 1 temp[l + 1: r] = 1 elif temp[l] == 1 and temp[r] == 2: if np.count_nonzero(temp[r: n + 1] == 2) & 1: temp[r] = 2 else: temp[r] = 1 temp[l + 1: r] = 1 elif temp[l] == 1 and (temp[r] == 0 or temp[r] == 3): temp[r] = 2 temp[l + 1: r] = 1 elif temp[l] == 1 and temp[r] == 1: temp[l + 1: r] = 1 elif (temp[l] == 0 or temp[l] == 3) and temp[r] == 1: temp[l] = 2 temp[l + 1: r] = 1 else: # l == r if temp[l] == 0: temp[r] = 3 i = 0 flag_left = False num_left = None ans = [] while i < n + 1: if temp[i] == 2 and not flag_left: flag_left = True num_left = i elif temp[i] == 2 and flag_left: ans.append([num_left, i]) flag_left = False num_left = None elif temp[i] == 3: ans.append([i, i]) i += 1 return ans
@nikhil_a01
@nikhil_a01 Жыл бұрын
That is one of the craziest solutions I've ever seen anyone post. Either on KZbin or in the LeetCode forums. But props to you for sticking with it. I don't think enough people are willing to try really hard. Everyone's in a rush for interview prep and wants to look up the solution after 20 minutes.
@howitfeelslike5381
@howitfeelslike5381 Жыл бұрын
really nice dude ! huge respect for not giving up
@DanielRodrigues-bx6lr
@DanielRodrigues-bx6lr Жыл бұрын
jesus lol You even used numpy How long did it take you from start to end (pun intended)?
@BioInASec
@BioInASec Ай бұрын
I can not seem to implement a solution myself 😒😒
@janardannn
@janardannn 6 ай бұрын
i could do it, but with worse time complexity, recursive n^2 log n
@s49243
@s49243 Жыл бұрын
public int[][] merge(int[][] intervals) { Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); ArrayList output = new ArrayList(); output.add(intervals[0]); int index=0; for (int i = 1; i < intervals.length; i++) { int start = intervals[i][0]; int end = intervals[i][1]; int lastend = output.get(index)[1]; if (start
@edwardteach2
@edwardteach2 3 жыл бұрын
U a God
@nathamuni9435
@nathamuni9435 2 жыл бұрын
like meeting room.......
@tefradc
@tefradc 4 жыл бұрын
can you code using c++,that will be very helpful:)
@CostaKazistov
@CostaKazistov 3 жыл бұрын
class Solution { public: vector merge(vector& intervals) { sort(intervals.begin(), intervals.end(), less()); vector res; res.push_back(intervals.front()); for (int i = 1; i < intervals.size(); ++i) { int start = intervals[i][0]; int end = intervals[i][1]; int lastEnd = res.back().back(); if (start
@jamalyarfoor5798
@jamalyarfoor5798 Жыл бұрын
I got 6000ms solution
@andrewsucks7645
@andrewsucks7645 Жыл бұрын
you did not cover edgecases like this [[1,4],[0,4]]
@NeetCode
@NeetCode Жыл бұрын
If we sort based on start time I don't believe we have to worry about this one
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 181 М.
Merge Overlapping Intervals | Brute, Optimal with Precise TC analysis
22:35
SLIDE #shortssprintbrasil
0:31
Natan por Aí
Рет қаралды 49 МЛН
Жездуха 42-серия
29:26
Million Show
Рет қаралды 2,6 МЛН
LRU Cache - Twitch Interview Question - Leetcode 146
17:49
NeetCode
Рет қаралды 312 М.
Leetcode 128 - LONGEST CONSECUTIVE SEQUENCE
9:24
NeetCode
Рет қаралды 403 М.
The Dome Paradox: A Loophole in Newton's Laws
22:59
Up and Atom
Рет қаралды 1,1 МЛН
What is mathematical thinking actually like?
9:44
Benjamin Keep, PhD, JD
Рет қаралды 25 М.
10 Math Concepts for Programmers
9:32
Fireship
Рет қаралды 2 МЛН
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 462 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 741 М.
Top K Frequent Elements - Bucket Sort - Leetcode 347 - Python
13:13
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 328 М.
SLIDE #shortssprintbrasil
0:31
Natan por Aí
Рет қаралды 49 МЛН