DP 28. Longest Palindromic Subsequence

Поділитися
Вставка
  • Опубліковано 10 лют 2025
  • Lecture Notes/C++/Java Codes: takeuforward.o...
    Problem Link: bit.ly/3pvkqUd
    Pre-req for this Series: • Re 1. Introduction to ...
    a
    Make sure to join our telegram group for discussions: linktr.ee/take...
    Full Playlist: • Striver's Dynamic Prog...
    In this video, we solve the Longest Palindromic Subsequence, please watch the LCS Dp video before solving this.
    If you have not yet checked our SDE sheet, you should definitely do it: takeuforward.o...
    You can also get in touch with me at my social handles: linktr.ee/take...

КОМЕНТАРІ •

  • @johncenakiwi
    @johncenakiwi 2 роки тому +122

    As soon as you explained the reversing part, it clicked. Amazing video as always. Thank you very much!!!😀

  • @Harshit126
    @Harshit126 2 роки тому +17

    Understood, thank you so much. It all seems to be summed up within 14 mins or so but the hard work and story behind coming up with logic such as this one, by "simply reversing the string" is always next level!

  • @PiyushSharma-ud9qk
    @PiyushSharma-ud9qk 2 роки тому +162

    Tabulation code of LCS is very important guys...if you understand how values are getting filled in the table...you can solve this problem by yourself by thinking this problem in terms of lcs...it's the first problem of dp on strings which I have solved by myself. #Understood bhaiya❤️❤️

    • @PiyushSharma-ud9qk
      @PiyushSharma-ud9qk 2 роки тому +7

      @अभय बिष्ट @अभय बिष्ट here, we are supposed to find the palindrome subsequence whose length is as large as possible, right !!! Now the thing is are we care about a palindromic subsequence or palindromic substring. Just think & you can see you have to figure out the palindromic string which is nothing but the subsequence of the input string. If still, the thought process didn't strike ur mind let's take an example:-
      s1 = ababmna
      s2 = abadbefgha
      So the answer according to your thought process should be just "aba" I.e of length 3 but common subsequence of s1 & s2 ababa which is palindrome & also largest. You were just thinking of the cases where you would get a palindromic string iff it is a common substring but it is not the case every time as you can see in the above example. Hope this might help🙂🙂

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

      will you please send the link of lcs lectuare

    • @sandeepmourya8922
      @sandeepmourya8922 Рік тому +6

      @StarLorD are vedya, every every substring is also subsequence, but the opposite is not always true.

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

      @StarLorD bhai kyuki apan ko subsequence chaiye na , isliye , agar largest commom substring bolta tab second wali approach se kar dete

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

      @tanjiroSama2020 bab is also a subsequence brother , subsequence will takecare of the substrings as well

  • @anubhav_gupta_
    @anubhav_gupta_ Рік тому +15

    Thankyou Striver🙏🏻❤
    Before watching this video, I come up with two approaches by my own:
    1) We can do this in one string recursively, starting point ==> f(n-1,0).
    2) Find LCS of s and reverse(s).
    **Approach 1 code c++:
    class Solution {
    public:
    int f(int i, int j, string &s, int n, vector&dp){
    if(i < 0 || j > n-1) return 0;
    if(dp[i][j] != -1) return dp[i][j];
    if(s[i] == s[j]) return dp[i][j] = 1 + f(i-1,j+1,s,n,dp);
    else return dp[i][j] = max(f(i,j+1,s,n,dp), f(i-1,j,s,n,dp));
    }
    int longestPalindromeSubseq(string s) {
    int n = s.length();
    vectordp(n,vector(n,-1));
    return f(n-1,0,s,n,dp);
    }
    };
    **Approach 2 code c++:
    class Solution {
    public:
    int longestCommonSubsequence(string s1, string s2) {
    int n1 = s1.length(), n2 = s2.length();
    vectordp(n1+1,vector(n2+1,0));
    dp[0][0] = 0;
    for(int i1 = 1; i1

    • @ayushrawat215
      @ayushrawat215 6 місяців тому

      genius brother

    • @vatsaljain662
      @vatsaljain662 5 місяців тому

      thought of the same thing coz it was more intuitive brother

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

    the moment u said char at start and char at end got the idea and able to solve the que. Thanks

  • @hetavvakani7025
    @hetavvakani7025 2 роки тому +10

    Did what you said in LCS tutorial "For string it is either matching or not matching" and solved it using two pointer and dp.Thank You!!!

  • @mayank_singh_43
    @mayank_singh_43 Рік тому +8

    I cant believe that after reaching to 29th video of this series , I can think DP solutions by myself and I can solve those questions, thnx alot striver bhaiya, you are doing great work

  • @pavan_talluri6540
    @pavan_talluri6540 9 місяців тому +1

    Thanks!

  • @KrishnaGuptaTech
    @KrishnaGuptaTech 2 місяці тому

    As soon as I saw title, approach hit my mind, thanks striver, understood !!!

  • @dorisalarushika5460
    @dorisalarushika5460 2 роки тому +2

    I did it without watching explanation itself by the knowledge of previous videos truly thank u

  • @kathanvakharia
    @kathanvakharia Рік тому +12

    Understood....Completed (28/56). HALF WAY THROUGH🙌🙌

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

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

  • @aps8874
    @aps8874 2 місяці тому

    The first problem of DP on Strings that I solved on my own. Thanks❤

  • @JeevanGaikwad-G1
    @JeevanGaikwad-G1 2 роки тому +3

    Amazing. Thanks a lot for bringing up this DP series and putting hard work for a good explanation. Now DP problem look easy 😀

  • @deepakjain4481
    @deepakjain4481 9 місяців тому +3

    we can also do it by using longest common subsequence where we will start the dp by 0 to len -1 of string then if the character matches we will recursively make the i and j move close both a unit step and if not we will thereforce use left right and when i crosses j we will return

  • @fanofabdevillersandmathslo5960
    @fanofabdevillersandmathslo5960 5 місяців тому

    Understood
    wow this is getting bigger and better with each video.....

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

    I did this in the single String itself by recursive 2 pointer f(0, n -1). It is working great and superbb !! and also faster than the lcs(s, reverse(S)) method in this video😁😁😁😀

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

    My goodness, who would have thought there can be such a thing which will lead to the ans of LPS...........Amazing Intuition Bhaiyaaaaaaaaaaaaa Hatssssss Offfffffff !!!

  • @VishalYadav-gk1kg
    @VishalYadav-gk1kg 7 місяців тому +1

    Very nice explanation sir, Thank you!

  • @AlokLaha-te2pd
    @AlokLaha-te2pd 7 місяців тому

    Thanks striver for explaining the reverse logic.

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

    after watching your previous video, I can solve this question on the fly before watching this videooo.!

  • @chitreshmourya-sz6kb
    @chitreshmourya-sz6kb Рік тому

    gazab explanation bhai , understood just in a half video

  • @himanshuagrawal8012
    @himanshuagrawal8012 2 роки тому +5

    #UNDERSTOOD LCS is amazing..we can solve a lot of using that logic only...Thanks

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

    I did this question without studying recursion from gfg, tried to make head and tail out of it using debugger, that was a nightmare, now after studying recursion I can't describe how easy this is .

  • @anmol3749
    @anmol3749 Місяць тому

    Understood
    Thank you Striver🙌🙌

  • @user-of5qt4yn5j
    @user-of5qt4yn5j 4 місяці тому

    understood striver,god may bless u for your efforts

  • @amishasahu1586
    @amishasahu1586 2 роки тому +9

    Hey Sir!!
    How do it print the longest palindromic substring.

  • @VishalPatel_imvishal
    @VishalPatel_imvishal Рік тому +2

    That feeling of solving the DP question by self without watching the solution at all.
    Thanks a lot, Striver. I was scared to touch the DP before :D but not anymore :) ❤

  • @21F142_RITHIKAP
    @21F142_RITHIKAP 8 місяців тому +1

    You explained the concept of longest palindromic Subsequence using LCS, that is understandable. But in some case , It does not produce output as palindrome

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

    UNDERSTOOD...!!!
    Thank you striver for the video... :)

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

    Thanks striver❣️

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

    Hey Striver thanks man. Great explaination. I got the gist of how to approach n solve this question the moment you said reverse here 4:27

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

    You are amazing. Really wonderful Explanation.

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

    Amazing explanation , thanks Striver

  • @ssc_-kn6os
    @ssc_-kn6os 2 роки тому +2

    Problem Link : www.codingninjas.com/codestudio/problems/longest-palindromic-subsequence_842787?leftPanelTab=0

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

    This was just simply amazing !!

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

    understood bhaiya ❤

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

    Here is the link to the practise problem -->> www.codingninjas.com/codestudio/problems/longest-palindromic-subsequence_842787

  • @cinime
    @cinime 2 роки тому +2

    Understood! What a fantastic explanation as always!!

  • @prabhakaran5542
    @prabhakaran5542 10 місяців тому +1

    Understood❤

  • @adarshkumar167
    @adarshkumar167 2 роки тому +2

    Just after writing the second string, my mind clicked.

  • @gaura-krishna
    @gaura-krishna 2 роки тому

    Thank you very much brother. Thanks a lot. Accha lagta hai jab sawal ho jata hai...

  • @madhavkumar-my9zh
    @madhavkumar-my9zh 2 роки тому +5

    we can even reduce the time complexity by not generating a new string s2 which is reverse of s1.
    Insted of this what we can do instead of s1[i-1] == s2[j-1] we can write s1[i-1] == s1[n--1-(j-1)] (also s1[n-j]) .
    full code ->
    int longestPalindromeSubseq(string s) {
    string t;
    int n = s.size();
    vector dp(n+1,0);
    for(int i=1; i

  • @adarshdubey1784
    @adarshdubey1784 2 роки тому +14

    For those who think, the same approach will also work for the longest palindromic substring, Bro it will not work !!
    For example, S = "abacdfgdcaba", S'
    = "abacdgfdcaba".
    The longest common substring between S and S'
    is "abacd". Clearly, this is not a valid palindrome.

    • @jayeshshrivastava5424
      @jayeshshrivastava5424 2 роки тому +2

      Do you have solution for lpsubstring

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

      @@jayeshshrivastava5424 you can watch this video for better understanding ua-cam.com/video/WpYHNHofwjc/v-deo.html

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

      Yes u r right
      Did you get any other solution for it?

    • @HardikBhasin-d5u
      @HardikBhasin-d5u 14 днів тому

      same for abcdefdefag

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

    Understood 🙏

  • @neerajchoithwani6975
    @neerajchoithwani6975 15 днів тому

    Striver is a good explainer .❤

  • @030-sham
    @030-sham Рік тому

    thank you striver

  • @ntgrn-pr5yx
    @ntgrn-pr5yx 3 місяці тому

    Understood thank you striver

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

    I came up with the solution without watching the video. Damn man, thanks !!!!!!

  • @devbhojani9274
    @devbhojani9274 9 місяців тому +1

    I solved it little differently(similar approach tho)... I used only a single string and kept one pointer(l) at 0 and the other pointer(r) at s.length()-1... then if the characters at these indexes are same and l!=r, add 2 to the answer, if l==r, add 1 to the answer... if the characters are not same, call the function twice, once with l+1,r and then with l,r-1 and take the max of the two...
    class Solution
    {
    public int longestPalindromeSubseq(String s)
    {
    int dp[][] = new int[s.length()][s.length()];
    for(int i = 0; i

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

    Understood, sir. Thank you very much.

  • @triptiverma382
    @triptiverma382 Місяць тому

    Too good explanation 😀

  • @karppakavallisaravanan9686
    @karppakavallisaravanan9686 5 місяців тому

    Amazing explanation

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

    understood bro, thanks a lot for making this question look so simple.

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

    Mind blowing solution

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

    fantastic approach! I always thought that you would have to cut the string into 2 parts and find the lcs in O(n^2 * k) lol

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

    Understood, thank you for the awesome explanation

  • @soniamalik4929
    @soniamalik4929 2 роки тому +2

    Understood Sir

  • @johnsimon8158
    @johnsimon8158 3 місяці тому

    Thanks for this awesome content

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

    Absolutely brilliant.

  • @VikashYadav-px8ei
    @VikashYadav-px8ei Рік тому +1

    Understood 🎉

  • @shubodeepsengupta5506
    @shubodeepsengupta5506 2 роки тому +5

    In a similar way if we are given to find the longest palindromic substring can we just reverse it and apply the longest common substring approach???
    I tried applying the same approach it works most of the time but in some cases it does fail
    If u could please explain why does that happen and put some light on it that would be really great
    And keep up the good work 👏

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

      No this approach doesn't work for longest common sub string you can try it out on leetcode, and see a solution section there they explain the reason very well hope this will help

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

      ​@@adityakhare2492substring is continuous. Subsequence is there might be some letters in between
      Let's take an example :- aacakdacaa
      He if you say longest palindrome is aca only!
      Longest palindrom subsequece is aaca ( k or d ) acaa
      I hope you get the answer.

    • @Akshay-jx6si
      @Akshay-jx6si 11 місяців тому

      @@vengalrao5772 aaca is not a palindrome

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

    Understand Sir, Thank you very much

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

    This is so good ❤ now dp is easy because of you.. US ❤

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

    Understood. Thanks for the video!

  • @khoivo1074
    @khoivo1074 Місяць тому

    clear and perfect

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

    understood, did this by myself.

  • @raghavmanish24
    @raghavmanish24 5 місяців тому

    understood ...........thanke striver

  • @AbhishekGupta-xz1gd
    @AbhishekGupta-xz1gd Рік тому

    Understood, great explanation

  • @shivansh.speaks
    @shivansh.speaks 7 місяців тому +1

    gazabbbbbb yrrrr❤❤🔥🔥🙌🙌🙏🙏✨✨

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

    Striver da...I found out another method....through not so much good....but still....let me share it...
    I took two indices lead and lag....initialised lead to 0 and lag to the end of the string....and checked whether [lead] = s[lag] like that else lead + 1 or lag -1 ......like this...and the base case as if (lead>lag) return 0 and if (lead== lag) return 1 ....like this.....and thanks da....it was only for your dp series that i am able to come up with my own solutions ......

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

    UNDERSTOOD!!!🔥🔥🔥🔥🔥🔥

  • @hashcodez757
    @hashcodez757 6 місяців тому

    "UNDERSTOOD BHAIYA!!"

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

    understood Thanks raj😁

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

    Halfway done 👍 🙌

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

    Understood! Thanks!

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

    Understood, thanks!

  • @himanshuagrawal8012
    @himanshuagrawal8012 2 роки тому +5

    Please update the link with LPS , its actually of LCS

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

    this is the best dp series man Understood bhaiya ❤❤

  • @Whyush7
    @Whyush7 2 роки тому +2

    please update the problem link in the description :)

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

    Superb Sir, Understood

  • @tasneemayham974
    @tasneemayham974 Рік тому +3

    Striver, I have a question: What if it was printing longest palindromic substring. The problem is for this string s = "aacakdbacaa" its inverse is string t = "aacabdkacaa". What the program is doing is taking the longest common substring which is acaa. This is not a palindrome. What is the optimal solution, please? May anyone help if they can?

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

      Answer will be :- aaca(k or d or b ) acaa
      Once check it again
      We have to find longest subsequence palindrome right !

    • @HardikBhasin-d5u
      @HardikBhasin-d5u 14 днів тому

      @@vengalrao5772 then please help for this substring "abcdefdefag" its reverse is "gafedfedcba" and the lcs is afdea which is not a palindrome and there's no palindrome possible other than a single char then how will this work?

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

    "Solved without seeing the video " logic is improving day by day

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

    Understood thank you so much

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

    Where I can get the java code for this problem sir I cannot find in the description notes

  • @75dhruvkhanna71
    @75dhruvkhanna71 Рік тому +1

    the reversing method won't work for palindromic substring

  • @amansamal8233
    @amansamal8233 2 роки тому +2

    ❤❤ understood

  • @akashkumarsingh3595
    @akashkumarsingh3595 2 роки тому +2

    Understood🔥🔥

  • @johncenakiwi
    @johncenakiwi 2 роки тому +5

    Hey Striver! Can you please do a video on LC 139 . Word Break??

  • @shrimanghugare8911
    @shrimanghugare8911 Місяць тому

    Understood Everything

  • @BOSS-s6w8w
    @BOSS-s6w8w Рік тому

    correct the problem link
    everything is excellent

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

    Intuition is pretty basic, palindromes read back the same as left to right, i.e. in a 3 character string, character at index 1 reads the same as character at index 3, similarly 2 and 2, 1 and 3. If you reverse the original string the indices are reversed, hence you can just keep comparing from left to right to check for palindrome.

  • @shreyasingh4680
    @shreyasingh4680 Рік тому +2

    this would fail for the cases like aabadkjcabaa
    what to do in that case

    • @rushidesai2836
      @rushidesai2836 Місяць тому

      I was thinking this only. Where is the palindrome check? I agree that the palindromic subsequence if exists, will maintain order on reverse. But what if the palindromic subsequence does not exist at all.

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

    Understood Sir.

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

    Understood 🙂🙂💚

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

    understood striver !!

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

    Can we similarly solve Longest Palindromic Substring using finding Longest Common Substring ?

  • @moksh7130
    @moksh7130 Місяць тому

    Excellent

  • @SethuIyer95
    @SethuIyer95 10 місяців тому

    I did this on my own 😎understood

  • @shivanssingh4897
    @shivanssingh4897 2 роки тому +2

    Hi Striver, request you to kindly cover Longest Palindromic Substring. It doesn't work with the logic of Longest Common Substring. Thanks

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

      Yes, with same logic it will fail for string="aacabdkacaa" for Longest Common Substring

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

      @@tanujkamde3557 did you find any answer for it, getting the same test case prob