DP 43. Longest Increasing Subsequence | Binary Search | Intuition

  Рет қаралды 179,812

take U forward

take U forward

Күн бұрын

Lecture Notes/C++/Java Codes: takeuforward.org/dynamic-prog...
Problem Link: bit.ly/3rVoIoq
Please watch the video at 1.25x for a better experience.
Pre-req for this Series: • Re 1. Introduction to ...
a
Make sure to join our telegram group for discussions: linktr.ee/takeUforward
Full Playlist: • Striver's Dynamic Prog...
In this video, we solve the Longest Increasing Subsequence problem using Dynamic Programming
If you have not yet checked our SDE sheet, you should definitely do it: takeuforward.org/interviews/s...
You can also get in touch with me at my social handles: linktr.ee/takeUforward

Пікірлер: 374
@takeUforward
@takeUforward 2 жыл бұрын
let me know in the comments, if this blew your mind or not :P
@prathamchoudhary6244
@prathamchoudhary6244 2 жыл бұрын
Great explanation!
@jaideepsingh7955
@jaideepsingh7955 2 жыл бұрын
Sir in amazon online interview, is it like leetcode where we have to complete a given function only, or we have to do all the input/output, construct trees/graphs etc. also ?
@Superheroic_Anime
@Superheroic_Anime 2 жыл бұрын
Mind blowing bhaiya
@ShivaniSinghYadav-sm3ee
@ShivaniSinghYadav-sm3ee 2 жыл бұрын
My mind flew away and now I am chasing it 😌🥴
@KapilKumar-ig6df
@KapilKumar-ig6df 2 жыл бұрын
lower_bound returns an iterator. How your code compiled by returning an index?
@Joselson14
@Joselson14 7 ай бұрын
This has been the most succinct explanation that I could find on KZbin. Thank you so much for your dedication.
@gaurishukla9177
@gaurishukla9177 2 жыл бұрын
Dude you were the only one who could explain why this worked!! loved it!!
@rishika6525
@rishika6525 2 жыл бұрын
thanks for giving the intutution behind, really makes the solution more meaningful, rather than feeling like we just gotta cram it
@-harshayadav
@-harshayadav 2 жыл бұрын
in java it returns the index of the search key, if it is contained in the array. otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key. int pos=Collections.binarySearch(temp,arr[i]); if(pos
@dhanashreegodase4445
@dhanashreegodase4445 2 жыл бұрын
i don't know why ppl leave videos like this wdout giving a like. there are currently 8k+ views and only around 400 likes. btw awesome content !!!!!!!!!thanks
@parthsalat
@parthsalat 2 жыл бұрын
Some men just want to watch the world burn 🔥
@parvathipillaiii
@parvathipillaiii 21 күн бұрын
and now its 172K views and 6.4k likes loml
@CostaKazistov
@CostaKazistov 2 жыл бұрын
Perfect explanation of the intuition behind this solution. Nice work! 👍👍
@AnkitJosh
@AnkitJosh Жыл бұрын
thank you ! the intuition was very helpful. for anyone looking to generate the actual sequence you can't do it using binary search. You would need a segment tree !
@rishabhthakur7494
@rishabhthakur7494 Жыл бұрын
At 11:15 the 2 will come after 1,even though nothing will change,just reminding.
@aeroabrar_31
@aeroabrar_31 Жыл бұрын
You know what , I just paused at this timestamp and came into the comment section to find whether i was the only one who spotted the mistake and found your comment.
@samratgupta731
@samratgupta731 Жыл бұрын
@@aeroabrar_31 +1 mate
@vivekvardhankaranam2027
@vivekvardhankaranam2027 Ай бұрын
i think 4 after that 1 has to be changed
@sameersahu4569
@sameersahu4569 2 жыл бұрын
The concept of lower bound was so amazing...Thank you
@Abhishek-yy3xg
@Abhishek-yy3xg 2 жыл бұрын
Java Solution: static int longestSubsequence(int size, int arr[]) { // using binary search ArrayList ans = new ArrayList(); ans.add(arr[0]); int len = 1; for (int i = 1; i < size; i++) { if (arr[i] > ans.get(ans.size() - 1)) { ans.add(arr[i]); len++; } else { int indx = binarySearch(ans, arr[i]); ans.set(indx, arr[i]); } } return len; } static int binarySearch(ArrayList ans, int key) { int low = 0; int high = ans.size() - 1; while (low
@yogeshvishwakarma596
@yogeshvishwakarma596 2 жыл бұрын
code: int lengthOfLIS(vector& nums) { vector temp; temp.push_back(nums[0]); for(int i(0);i temp.back()){ temp.push_back(nums[i]); }else{ int ind = lower_bound(temp.begin(),temp.end(),nums[i]) - temp.begin(); temp[ind] = nums[i]; } } return temp.size(); }
@sharcodes
@sharcodes Жыл бұрын
Thank You so much Bro
@NARUTOUZUMAKI-bk4nx
@NARUTOUZUMAKI-bk4nx 7 ай бұрын
Understood, Thanks for providing every possible intuition for Longest Increasing Subsequence
@kartikey3695
@kartikey3695 2 жыл бұрын
For those who are wondering how is 'ind' calculated :- ind = lower_bound(temp.begin(),temp.end(),arr[i]) - temp.begin();
@harshkushwaha5052
@harshkushwaha5052 2 жыл бұрын
thanks bro u saved my time
@arunabhgupta9082
@arunabhgupta9082 2 жыл бұрын
you can also use auto ind = lower_bound(temp.begin(),temp.end(),arr[i]); *ind = nums[i];
@mrigankshigupta9859
@mrigankshigupta9859 2 жыл бұрын
can you please explain this line of code ?
@user-fz9ye6yk9y
@user-fz9ye6yk9y Жыл бұрын
@@mrigankshigupta9859 basically you used auto to declare i, so it returns an iterator. *i is to approach the value where i points at.
@meetabhashiniparida9417
@meetabhashiniparida9417 Жыл бұрын
can u just explain me why at 11:09 we overwrite 1 with 2...that wont become a subsequence then right?
@anshverma2921
@anshverma2921 9 ай бұрын
so sorry for my words but this optimization is so fucking good. Seriously, so many approches for a single question damm. honestly sir if u want u can just give the best approch and finish it but u r taking us step by step and make us undersatnd the actuall concepts. i m following ur playlist from the starting but after this question not able to stop myself from getting jump into the cmnt box. Really thank u sir for such a best ever playlist.
@stith_pragya
@stith_pragya 6 ай бұрын
UNDERSTOOD............Thank You So Much for this wonderful video.......🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@kolawoleabdulrahman
@kolawoleabdulrahman 9 ай бұрын
awesome content. the only binary search approach I could find online as well and i understood. great video
@sagarmittal8627
@sagarmittal8627 2 жыл бұрын
This method is so good !! Much better TC and SC with such a short code !
@vikashkumar7762
@vikashkumar7762 2 жыл бұрын
Intution is superb... And Striver choice question is awesome :)
@vishalvishwakarma1760
@vishalvishwakarma1760 2 жыл бұрын
MIND BLOWING MAN! LOVED THE EXPLANATION.
@piyushsaxena7399
@piyushsaxena7399 2 жыл бұрын
the explanation is soooooooooooo goood, im really enjoying your dp series. i understand everything easily and enjoy it a lot. u make learning these concepts so easy to remember. thanks a lot
@sarthakjohnsonprasad3909
@sarthakjohnsonprasad3909 4 ай бұрын
Striver, trust me you have insane explanation skills.
@DivyaKumari179
@DivyaKumari179 Ай бұрын
Understood!!! Thanks for this amazing series 🎉
@Zasyg
@Zasyg 2 жыл бұрын
For all the java peeps out there Use this function instead of lower bound static int ceil(int key, List lst){ int low = 0 , lst = lst.size() - 1; int ans = -1; while(low
@satyamgupta1446
@satyamgupta1446 Жыл бұрын
int l = 0 , h = li.size() - 1; while(lnums.get(mid)) l=mid+1; else h=mid-1; } return l
@ananyagupta1409
@ananyagupta1409 4 ай бұрын
This was really well made !! Kudos!!!
@anshulagarwal6682
@anshulagarwal6682 2 жыл бұрын
Very good series in which we solve a same question by different methods.
@soumyakantigiri
@soumyakantigiri 2 ай бұрын
Wow, the only place where I need to come back since no other place helps me with the intuition.
@d_0364
@d_0364 21 күн бұрын
another O(nlogn) approach, kind of intuitive: Note: first do the space optimization using only one array (only *dp* and not *dp* with *cur* ) and analyze how the table is getting filled. make a duplicate array of pair {nums[i],i} and sort them. Lets name this array arr2. Now, the dp table is filled with "i" going n -> 0 as dp(prev) = max( dp(prev), 1+dp(i)) which essentially means that any number less than number at current index "i" will take its max i.e. { arr[i] > arr[prev] } and { i > prev } are the two conditions and then we can do dp[prev] = max(dp[prev], 1+dp[i]). thus we find the lower_bound of the current element arr[i] in arr2 and since arr2 is sorted, we go to all elements to left side of the lower_bound of arr[i]. as arr2 has size n and we are finding each arr[i] using binary search, this makes the complexity O(nlogn). Sorting also takes O(nlogn) so overall it works in O(nlogn).
@muditkhanna8164
@muditkhanna8164 10 ай бұрын
the most perfect N log N solution out there for LIS.
@deepakbhoria4172
@deepakbhoria4172 9 ай бұрын
Awesome video by Striver as always!!! Java also has ceiling methods for TreeSet, TreeMap. Because we are inserting in such a way sequence is kept increasing even after deletion and reinsertion, below will get accepted as well: public static int longestIncreasingSubsequence(int arr[]) { //Your code goes here TreeSet myset = new TreeSet(); myset.add( arr[0] ); for( int i = 0; i < arr.length; i++ ){ if( arr[i] > myset.last() ){ myset.add( arr[i] ); } else { //Map.Entry entry = myset.ceilingEntry( arr[i] ); Integer ceilValue = myset.ceiling( arr[i] ); if( ceilValue != arr[i] ){ myset.remove( ceilValue ); myset.add( arr[i] ); } } } return myset.size(); }
@ronakslibrary8635
@ronakslibrary8635 Жыл бұрын
Thanks for letting me know thre concept of Upper Bound and lower bound
@varunsharma1889
@varunsharma1889 2 жыл бұрын
Great explanation. And also credit to people who invented and came up with this idea 💡. That's tough.
@Tunbumbum
@Tunbumbum 8 ай бұрын
great explanation I love it, thank you sir
@user-yc2lm3mr3m
@user-yc2lm3mr3m Ай бұрын
Awesome explanation bro, thanks❤
@mohammadyahya78
@mohammadyahya78 5 ай бұрын
Wow your explanation is super
@DevashishJose
@DevashishJose 6 ай бұрын
Understood, thank you so much.
@SurajVT
@SurajVT Жыл бұрын
Java guys can use TreeSet from the Collection framework. // Code public int lengthOfLIS(int[] nums) { TreeSet ts = new TreeSet(); ts.add(nums[0]); for(int i=1; i
@nikhilsanaye7494
@nikhilsanaye7494 Жыл бұрын
Time complexity?
@coding8000
@coding8000 2 жыл бұрын
Understood, thank you sir, you are god to me , I worship striver Everyday. thanks.
@codingp110
@codingp110 2 ай бұрын
Bhaiya tussi great ho!
@andreasleonidou3620
@andreasleonidou3620 Жыл бұрын
Great explanation! Well understood, thanks!!
@pranoymukherjee3319
@pranoymukherjee3319 2 жыл бұрын
This is the best intuition I have ever seen for LIS using BS, code and explaination is everywhere but intuition 🔥🔥
@rishav144
@rishav144 2 жыл бұрын
Great explanation ...pls continue like this
@kamleshsinghbisht5569
@kamleshsinghbisht5569 Жыл бұрын
The concept of array could also be understood in this manner: Basically the ith element of temp array means that the longest increasing subsequence whose greatest element is temp[i] has a length of i+1. In the Algorithm what we are basically doing is that we are replacing the current element with it's best place in temp vector. By best place I mean that the place at which current element is the greatest element in the longest increasing subsequence. Let the index of that best place be ind(0 based indexing). Then ind+1 is the length of the longest increasing subsequence whose greatest element is the current element.
@gagankainthola8454
@gagankainthola8454 2 ай бұрын
i feel this approach in not at all intuitive but thanks for the explanation bhaiya:)
@utkarshkhairnar371
@utkarshkhairnar371 2 жыл бұрын
No need to update the temp if the index we got by lower_bound is not n-1,right?
@sayandey1131
@sayandey1131 Жыл бұрын
Just a small correction: lower_bound() gives index of first element which is greater than or equal to the target element. For getting index of 1st element, strictly greater than target element, we need upper_bound(). Anyway, great video as ever 🔥
@satvrii
@satvrii Жыл бұрын
No bro, lower bound hi hoga
@ujjawalraj6096
@ujjawalraj6096 Жыл бұрын
Haan to lower bound is we all required if the element is present then we have to replace with the same elements if not then find first greater one
@theresilientpianist7114
@theresilientpianist7114 6 күн бұрын
absolute treat
@prashantmishra-yw4xu
@prashantmishra-yw4xu 4 ай бұрын
great intuition striver
@cinime
@cinime 2 жыл бұрын
Understood! Thank U so much as always!!
@gamengoaituyen4432
@gamengoaituyen4432 Жыл бұрын
that so useful, i have got the hang of its working after watching this video
@singleslit2024ICPCgrind
@singleslit2024ICPCgrind 3 ай бұрын
thank you Striver:)
@the.stupid07
@the.stupid07 6 ай бұрын
good explanation 👍👍👍
@prashanjeetkumar1999
@prashanjeetkumar1999 13 күн бұрын
understood!!
@ratinderpalsingh5909
@ratinderpalsingh5909 Жыл бұрын
Understood, sir. Thank you very much.
@Tejaswita872
@Tejaswita872 6 ай бұрын
Nice explanation
@AnkitVerma-yn3ku
@AnkitVerma-yn3ku 4 ай бұрын
The intuition behind the binary search lies in the fact that we replace considerably bigger elements with smaller ones with the possibility that there are high chances that smaller elements will be smaller than upcoming bigger elements thereby forming LIS as compared to relatively existing bigger elements having possibility of being smaller than upcoming new elements meanwhile also maintaining max LIS list length up to some index i.
@prabhakaran5542
@prabhakaran5542 2 ай бұрын
Understood ❤
@daumtto
@daumtto 7 ай бұрын
Dude ur the best
@ITACHIUCHIHA-dr8sz
@ITACHIUCHIHA-dr8sz 2 жыл бұрын
Code to print LIS : www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/
@tarunsahu2365
@tarunsahu2365 Жыл бұрын
what a great explanation simply loved it
@prathamchoudhary6244
@prathamchoudhary6244 2 жыл бұрын
I have been following this series right from the beginning and found it to be the best on youtube . Thank you striver for this awesome playlist.
@UECAshutoshKumar
@UECAshutoshKumar Ай бұрын
Understood!!!
@no---on
@no---on 7 ай бұрын
If I want to print the subsequence then how I can do this, the subsequence is changing and we are inserting the new element into a vector which is actually not a subsequence. I got the approach for finding but if i have to print it then ?
@3darpan
@3darpan 2 жыл бұрын
Striver, this is just perfect !
@lakeshkumar1252
@lakeshkumar1252 Жыл бұрын
thanks for the easy and awesome explanation sir
@rushikeshdeshpande8809
@rushikeshdeshpande8809 Жыл бұрын
I was searching for this explanation everywhere
@roughero1353
@roughero1353 10 күн бұрын
What if the question was modified a bit and asking for non decreasing sub sequence instead of strictly increasing sub sequence, then in that case we cannot simply replace elements in the list right? So do we just insert these elements into the list? Or create a list of pair and if we have a duplicate we just increment count?
@dheerajshukla7008
@dheerajshukla7008 Ай бұрын
understand sir
@shivisingh9975
@shivisingh9975 3 ай бұрын
Understood!
@rimpiranibaruah7922
@rimpiranibaruah7922 8 ай бұрын
DOUBT If for arr={1,7,8,4,5,6,-1,9} say we are at i = 4, arr[i] = 5 and our temp is {1,4,8}..Now for comparing 5 in temp when we use lower_bound the range is [first, last) last not included..So isn't the comparison from temp.begin() to temp.end()-1? Since last is not included in the range.
@verma_jay
@verma_jay 9 ай бұрын
understood
@jatinbhatoya8420
@jatinbhatoya8420 2 жыл бұрын
JAVA SOLUTION - leetcode.com/problems/longest-increasing-subsequence/discuss/2172720/JAVA-oror-BINARY-SEARCH-oror-4-LINER
@meenakshiyadav7471
@meenakshiyadav7471 2 жыл бұрын
no one can teach like you sir
@RohitKumar-dy2gc
@RohitKumar-dy2gc 8 ай бұрын
amazing
@hiteshmehra361
@hiteshmehra361 28 күн бұрын
Is there any proof for binary search replacement method that it will not affect the LIS length?
@dhruvalkushwaha5132
@dhruvalkushwaha5132 2 жыл бұрын
I think we have to use an iterator for "ind" here because lower_bound will not return the index as int here. Can anyone clarify this?
@takeUforward
@takeUforward 2 жыл бұрын
We can subtract first iterator to get index
@tvwanderer7729
@tvwanderer7729 4 ай бұрын
Understood.
@l047vedanglokhande3
@l047vedanglokhande3 Жыл бұрын
Was looking for this approach 😱👍
@varunaggarwal7126
@varunaggarwal7126 Жыл бұрын
at 14:57, I think The size() function does not recalculate or iterate over the elements each time it is called, so it has a constant time complexity.
@gauravtiwary1839
@gauravtiwary1839 Жыл бұрын
Yes, the size() function for a std::vector in C++ has a time complexity of O(1).
@muditkhanna8164
@muditkhanna8164 10 ай бұрын
@@gauravtiwary1839 i've been programming for 4 years and i didn't knew that the size function has 0(1) TC. can you please share the algo for size function. I can understand what if a vector is already initialised for ex: vectorvec={1,2,3,4,5,6,7,8,9}; is vec.size(); 0(1)tc here also?
@immortal6978
@immortal6978 8 ай бұрын
Understood bro
@JAY-rm8pj
@JAY-rm8pj 2 жыл бұрын
Firstly a lots of thanks for delivering such an amazing content in an understandable way.... But one doubt...how does such intuition strikes to anyone while solving such questions...coz if this intuition strikes to anyone then it means that he is as equal as...a researcher/expert who has already developed such an algorithm for this question....
@rajeshsingh-mv7zn
@rajeshsingh-mv7zn Жыл бұрын
You can't form this solution in a 40min interview, if you've not seen it earlier
@shivasai7707
@shivasai7707 Жыл бұрын
This is more like greedy we try to keep minimum values in lis so list can expand awesome explanation as always
@anukulgaurav3043
@anukulgaurav3043 2 жыл бұрын
this is mind blowing striver:)
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
understood,great series
@premduvvapu476
@premduvvapu476 10 ай бұрын
Understood
@yashchawla3729
@yashchawla3729 2 жыл бұрын
Osm explanation keep making this kind of videos
@saiyamsachdeva3354
@saiyamsachdeva3354 Жыл бұрын
bhaiya java me toh stl n hota toh humko lowerbound and upperbound ka code likhna padega??
@utkarshchandra9787
@utkarshchandra9787 Жыл бұрын
If array is [ 5 4 6] the output 3 Since we counting the number of indes shorter than ith index
@muditkhanna8164
@muditkhanna8164 10 ай бұрын
no that will not happen 5 will be overwritten by 4 and the array will be {4,6 } of length 2 and answer will be 2 not 3.
@lakshaygupta5911
@lakshaygupta5911 Жыл бұрын
really good explanation 😃
@ganeshkamath89
@ganeshkamath89 2 жыл бұрын
Thanks Striver. Understood.
@SuyashSoni248
@SuyashSoni248 Жыл бұрын
Not working for [0, 1, 0, 3, 2, 3], Expected: 4 Actual: 3
@dreamyme543
@dreamyme543 7 ай бұрын
Understood:)
@googleit2490
@googleit2490 8 ай бұрын
DP Revision : Uff bhai, how can I even forget this solution ;-; Had to watch the previous two videos too, to get to the O(N) solution ;-; Nov'20, 2023 03:30 pm (Happy Birthday to me... ;))
@soubhikghosh6564
@soubhikghosh6564 8 ай бұрын
Hi can anyone tell me if its possible to print LIS in o(nlogn) ? If yes, then how should the code look like?
@m-bk4um
@m-bk4um 8 ай бұрын
understand
@YeaOhYeahh
@YeaOhYeahh 8 ай бұрын
daaamnnn🔥
@ujjalsaha428
@ujjalsaha428 2 жыл бұрын
As always "understood" ❤️
@danb9047
@danb9047 Жыл бұрын
for binary search dont we need sorted array
@halchal41
@halchal41 Жыл бұрын
This algo of finding longest increasing subsequence by BINARY SEARCH is call patience sorting algorithm.
@rabiprakashshanitwarangal527
@rabiprakashshanitwarangal527 11 ай бұрын
space complexity should be length of the lis??
DP 44. Largest Divisible Subset | Longest Increasing Subsequence
14:39
take U forward
Рет қаралды 109 М.
DP 41. Longest Increasing Subsequence | Memoization
24:35
take U forward
Рет қаралды 293 М.
Secret Experiment Toothpaste Pt.4 😱 #shorts
00:35
Mr DegrEE
Рет қаралды 30 МЛН
Задержи дыхание дольше всех!
00:42
Аришнев
Рет қаралды 3,6 МЛН
DP 48. Matrix Chain Multiplication | MCM | Partition DP Starts 🔥
53:41
Nature's Incredible ROTATING MOTOR (It’s Electric!) - Smarter Every Day 300
29:37
DP 42. Printing Longest Increasing Subsequence | Tabulation | Algorithm
25:57
Can you solve the paper clip question for 2nd grade students?
11:06
MindYourDecisions
Рет қаралды 20 М.
DP 46. Longest Bitonic Subsequence | LIS
13:52
take U forward
Рет қаралды 77 М.
DP 52. Evaluate Boolean Expression to True | Partition DP
34:55
take U forward
Рет қаралды 83 М.