Remove Duplicate Letters | Why Monotonic Stack | Intuition | GOOGLE | Leetcode - 316

Поділитися
Вставка
  • Опубліковано 12 вер 2024
  • Similar Problem :
    Leetcode-1081 - leetcode.com/p...
    This is the 20th Video on our strings Playlist.
    In this video we will try to solve a very good Problem - Remove Duplicate Letters (Leetcode-316).
    I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
    We will do live coding after explanation and see if we are able to pass all the test cases.
    Problem Name : Remove Duplicate Letters
    Company Tags : GOOGLE
    My solutions on Github : github.com/MAZ...
    Leetcode Link : leetcode.com/p...
    My DP Concepts Playlist : • Roadmap for DP | How t...
    My Graph Concepts Playlist : • Graph Concepts & Qns -...
    My GitHub Repo for interview preparation : github.com/MAZ...
    Subscribe to my channel : / @codestorywithmik
    Instagram : / codestorywithmik
    Facebook : / 100090524295846
    Twitter : / cswithmik
    ╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
    ║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
    ╠╗║╚╝║║╠╗║╚╣║║║║║═╣
    ╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
    #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook

КОМЕНТАРІ • 124

  • @ravirajshelar250
    @ravirajshelar250 11 місяців тому +13

    Just saw a video of Vans Amen about it and understood nothing, just saw your video and understood everything. You really explain it very well.

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +2

      It means a lot to me Raj.
      Thank you for trusting my content ❤️😇🙏

    • @wearevacationuncoverers
      @wearevacationuncoverers 11 місяців тому +1

      Who is Vans Amen ?

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

      @@wearevacationuncoverers Another youtube creator who posts leetcode solutions, his leetcode solution posts are pretty detailed though.

    • @user-ub2is4rs4x
      @user-ub2is4rs4x 5 місяців тому

      First time heard this name.

  • @raisanjeeb42
    @raisanjeeb42 11 місяців тому +9

    Bhaiya, The way you make question feels so easy & interesting , You deserve appreciation !
    watched the video for 5 minutes and tried to solve it, I was able to solve it .
    There is something magic in your explanation!

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      it means a lot to me.
      Thank you so much 🙏❤️😇

  • @wearevacationuncoverers
    @wearevacationuncoverers 11 місяців тому +4

    Someone give this guy a reward ❤. Complete LEGEND

  • @codestorywithMIK
    @codestorywithMIK  11 місяців тому +4

    If anyone is interested in "Recursion" version (Take and Not Take) can refer to this code below :
    /*
    At ever character i have two choices - take or not take.
    I can take it if that character is not taken before.
    Once I reach out of bounds, i will see my temp string and keeping updating the result which is lexically smaller
    */
    class Solution {
    public:
    string result = "";
    int n;
    int unique_characters;
    void solve(int idx, string s, string temp, unordered_set st) {
    if(idx >= n) {
    if(result == "")
    result = temp;
    else if(temp.size() == unique_characters) {
    result = temp > result ? result : temp;
    }
    return;
    }
    if(st.find(s[idx]) == st.end()) {
    temp.push_back(s[idx]); //taking idx'th char
    st.insert(s[idx]);
    solve(idx+1, s, temp, st);
    //Removing it for trying "Not Taking this Char"
    st.erase(s[idx]); //Not taking idx'th char
    temp.pop_back();
    }
    solve(idx+1, s, temp, st);
    }
    string removeDuplicateLetters(string s) {
    n = s.length();
    unordered_set st;
    for(char &ch : s) {
    st.insert(ch);
    }
    unique_characters = st.size();
    st.clear();
    solve(0, s, "", st);
    return result;
    }
    };

  • @HarshMishra-cp7tj
    @HarshMishra-cp7tj 11 місяців тому +1

    Bhhaiya Subha Se colg me 3 4 ladke including me lge hue the is question ke peeche Logic to smjh gye the bas last moment me kuch test cases aakr phas gye the. But aapki video dekh kr ek dm logic smjh aa gya.
    Love from ghaziabad

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      Thank you 😇🙏
      So glad to hear ❤️❤️

  • @harshdixit2121
    @harshdixit2121 Місяць тому +1

    hey, I don't know your real name , but I have been following you from few weeks , and you are one of the educators I can connect with, I won't say best, cause that's relative and different people connect with different individuals , but for me, you are almost perfect explainer. I would love to connect with you on twitter, if you are, Thanks.

  • @ANEIESH
    @ANEIESH 11 місяців тому +2

    great story telling buddy, thank you for your explanation I was able to code with that story only.

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

      So glad to hear. Thank you for watching 😇❤️

  • @ManishKumar-zk5ky
    @ManishKumar-zk5ky 11 місяців тому +3

    Your content is too good sir Thanks for such content🤩

  • @AnandKumar-kz3ls
    @AnandKumar-kz3ls 11 місяців тому +2

    as you mentioned we will only pop if we have the same character which is on the top of the stack available in our remaining string just after watching 5 minutes i coded it by myself and passes
    277 / 290 test cases then realized if the chacater is already pushed in stack we dont need to take care of that and then get accepted here is my code
    class Solution {
    public:
    string removeDuplicateLetters(string s){

    int freq[26]={0};
    vector visited(26,false);
    stack stk;

    for(auto& c:s) freq[c-'a']++;

    for(auto& c:s){

    while(!stk.empty() && stk.top() > c && freq[(int)(stk.top()-'a')] > 0 && !visited[c-'a'] ){
    visited[(int)(stk.top()-'a')]=false;
    stk.pop();
    }

    if(!visited[c-'a']){
    stk.push(c);
    visited[c-'a']=true;
    }

    freq[c-'a']--;

    }

    string res;
    while(!stk.empty()) {
    res.push_back(stk.top());
    stk.pop();
    }

    reverse(res.begin(),res.end());
    return res;

    }
    };

  • @sachinmohanty4577
    @sachinmohanty4577 11 місяців тому +2

    this is the recursion+backtracking solution of today's LC potd (giving TLE but this is the first approach which came to mind hope it helps others)
    class Solution {
    public:
    string ans;
    void solve(int idx, string &s, string &temp, set&st2, set&st1){
    if(st1.size()==st2.size()){
    if(ans.size()>temp.size()){
    ans = temp;
    }
    if(ans.size()==temp.size())ans = min(ans, temp);
    return;
    }
    if(idx==s.size())return;
    // take only if the current char not in set
    if(st2.find(s[idx])==st2.end()){
    st2.insert(s[idx]);
    temp+=s[idx];
    // cout

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +2

      This is unbelievable. My recursion code is exactly similar to yours ❣❣❣❣
      I feel so proud and happy to see you coded this up. Thank you so much for sharing ❤❤❤❤

    • @sachinmohanty4577
      @sachinmohanty4577 11 місяців тому +1

      @@codestorywithMIK I am so so happy MIK for your comment 🥺❤️

  • @girikgarg8
    @girikgarg8 11 місяців тому +1

    I was struggling since the morning for this question, tysm for this explanation

  • @HealthyOm
    @HealthyOm 11 місяців тому +2

    Bhaiya aapke Vedios mai ek alag hi feel vibe hoti hain ❤❤❤❤❤❤

  • @khitijkarmakar
    @khitijkarmakar 11 місяців тому +2

    This channel is a goldmine that i found
    May you get more n more success bhai❤️

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      Thank you so much ♥️♥️🙏🙏😇😇

  • @MohitKumar-ys8jd
    @MohitKumar-ys8jd 11 місяців тому +1

    Very greatly explained. The question felt like a cakewalk. Thanks!!

  • @ssubhendu2114
    @ssubhendu2114 11 місяців тому +2

    aise story kbhi nhin sunethe❤❤❤

  • @kushal800
    @kushal800 11 місяців тому +1

    Phenomenal video aur Hindi me to mazaa hi aa Gaya

  • @parassaini8601
    @parassaini8601 11 місяців тому +3

    mast ek dum

  • @cgoxo
    @cgoxo 11 місяців тому +1

    Really loved your approach on how you explain the solution.

  • @rohitshah8904
    @rohitshah8904 11 місяців тому +2

    Couldn't think of stack. Great explaination

  • @knoxmacroboy7272
    @knoxmacroboy7272 11 місяців тому +1

    thanks for the intuition had thought of stack first but 2nd test case came out wrong with my approach because i tried to it like remove adjacent letters on duplicate case by sorting

  • @39_jatinjain4
    @39_jatinjain4 11 місяців тому +1

    great question with nice explanation

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

    Legendary explaination

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

    Thanks for the explaining this. But please update both the arrays in parallel during processing otherwise it difficult to follow in one go. 😢😢

  • @mdarifnufqqdugir3278
    @mdarifnufqqdugir3278 11 місяців тому +1

    Your channel is growing like boooooommm..and everyone knows the reason..they are in love with the story ❤me too😅

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      Means a lot. Thank you so much 😇❤️🙏

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

    Bro your explanation is perfect, thank you

  • @_PRANAYMATE
    @_PRANAYMATE 27 днів тому

    Nice Explanation mik bhaiyya here is the code of this using stack in java
    public String removeDuplicateLetters(String s) {
    char [] arr=s.toCharArray();
    int[] lastIndex=new int[26];
    boolean [] taken=new boolean[26];
    Arrays.fill(taken,false);
    for(int i=0;i i)
    {
    taken[stk.peek()-'a']=false;
    stk.pop();
    }
    stk.push(ch);
    taken[idx]=true;
    }
    StringBuilder result=new StringBuilder();
    while(!stk.isEmpty())
    {
    result.append(stk.pop());
    }
    return result.reverse().toString();
    }

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 11 місяців тому +1

    good explanation understood 👍

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

    story smjh aane k baad b roo diya bhai me, solution bnane me

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

      mene like kr dia, baaki sb tere solution ki tarah, tu king hai

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

    Sir, please bring some questions where the idea of Lexicographical order is infused!

  • @codeandtalk6
    @codeandtalk6 11 місяців тому +1

    ❤❤❤ this question came in oracle online assessment this year.

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

      Thank you so much for informing about this ❤️❤️

  • @honey6567
    @honey6567 11 місяців тому +2

    sir ye Sheldon Cooper Algorithm's hai --->
    class Solution {
    public:
    bool presentstack[26]={};
    int lastindex[26]={0};
    //sheldon cooper used
    int k ;
    string removeDuplicateLetters(string s) {
    stackst;
    //last index fetch from presentstack
    for(int i=0;s[i]!='\0';i++){
    lastindex[s[i]-'a']=i;
    }
    for(int i=0;s[i]!='\0';i++){
    char ch = s[i];
    if(!presentstack[ch-'a']){
    //check value that are present or not in stack
    while(!st.empty() and ch < st.top() and lastindex[st.top()-'a']>i){
    presentstack[st.top()-'a']=false;
    st.pop();
    }
    st.push(ch);
    presentstack[ch-'a']=true;
    }
    }
    k =s.size();
    string str ="";
    while(!st.empty()){
    str +=st.top();
    st.pop();
    }
    reverse(begin(str),end(str));
    return str;
    }
    };

  • @anuppatankar4294
    @anuppatankar4294 11 місяців тому +2

    Great Video 🔥

  • @AryanTomar_2025
    @AryanTomar_2025 11 місяців тому +2

    Sir is your graph playlist is complete or not?
    Btw it is very very very helpful ❤❤

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      Only 2-3 videos left.
      Will upload tomorrow soon 😇❤️🙏

  • @beinghappy9223
    @beinghappy9223 11 місяців тому +1

    Amazing explanation Sir

  • @tutuimam3381
    @tutuimam3381 11 місяців тому +2

    Nice❤❤❤

  • @AJ-fb9pk
    @AJ-fb9pk 11 місяців тому +1

    How do you explain your intuition of using a stack to the interviewer?

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      If you notice, when I input a character in the result, there are chances I will have to remove it if I find a better alternative (lexically smaller) . So removing the character from behind is the nature of stack only. The best data structure to handle such situations is stack. Hope this will make sense in the interview ❤️❤️

  • @teji644
    @teji644 11 місяців тому +1

    Just saw the thumbnail about monotonic stack and was able to solve😂

  • @honey6567
    @honey6567 11 місяців тому +2

    thank y sir

  • @shubhamrai8673
    @shubhamrai8673 11 місяців тому +1

    Sir Can you make a video of recursive solution of this question??

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

      Hi there,
      I have shared the recursive code in the comment and also in the GitHub link in the description. Give it a look, it’s simple based on take/not take concept.
      Really hope that will help 😇❤️🙏

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

    The story. uffff ❣
    masterpiece

  • @aman3210
    @aman3210 11 місяців тому +1

    bhaiya mst smjhaya ...thankyou++ ;

  • @sachinmohanty4577
    @sachinmohanty4577 11 місяців тому +1

    @codestorywithMIK
    Ye recursion se try karne ka kosis kiya mei take not take
    Take tab hoga jab set mei wo character nhi hoga pahle se and temp ek another string jisme wo character add hoga and jab idx== s.size() hoga and set1.size=set2.size ( set 1 s ke sare char ko store karega and set 2 take case wale char ko) higa tab sort kardenge temp ko and not take se pahle set2 se remove karenge and temp se pop back karenge!! Please MIk help with this logic

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

      Hi Sachin,
      Sounds like a valid approach. At ever character i have two choices - take or not take.
      I can take it if that character is not taken before.
      Once I reach out of bounds, i will see my temp string and keeping updating the result which is lexically smaller

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

      @@codestorywithMIK MIk i have posted my code in the comment just look at it once pls

  • @mohithadiyal6083
    @mohithadiyal6083 11 місяців тому +1

    Best explanation as always

  • @shivamtomar9658
    @shivamtomar9658 11 місяців тому +1

    thank you sir♥

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

    bhaiya ek leetcode ques hai Set matrix zeros please isper ek bnado code nd all please please

  • @souravjoshi2293
    @souravjoshi2293 11 місяців тому +1

    Guruji. Tussi great ho

  • @user-ub2is4rs4x
    @user-ub2is4rs4x 5 місяців тому

    Mast ekdm

  • @THOSHI-cn6hg
    @THOSHI-cn6hg 8 днів тому +1

  • @39_jatinjain4
    @39_jatinjain4 11 місяців тому +1

    if it is possible can u make videos on Leetcode contest questions

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

      I will soon start planning that once I get back to India soon 😇🙏

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

      👍

  • @theabhishek198
    @theabhishek198 11 місяців тому +1

    you are taking result to return the final result, that would be some extra space right ?

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      We usually dont consider the space taken to store result (that we have to return).
      But you can mention to the interviewer that you have taken this space for storing the result, apart from that we are not taking any extra space.

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

    Loved the story ❤❤❤

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

    bhaiya pair kahan hai apke 🙇‍♂🙇‍♂. You just made it easy .

  • @rajkrishanmahajan2373
    @rajkrishanmahajan2373 11 місяців тому +1

    i use MAP it little bit easy but it will take log n time extra for search 😅

  • @yikes3807
    @yikes3807 11 місяців тому +1

    thank u

  • @umeshbisht1054
    @umeshbisht1054 11 місяців тому +1

    Thanku bhaiya ❤

  • @avnish-wf8rv
    @avnish-wf8rv 11 місяців тому

    Sir Ye array wala you usme. (- 'a') wala concept kon se video mein explanin liya tha. ?

    • @k.vabhavmishra
      @k.vabhavmishra 11 місяців тому

      Sort by frequency daalo string question hoga usme kiya hoga

    • @avnish-wf8rv
      @avnish-wf8rv 11 місяців тому

      @@k.vabhavmishra th anks

  • @onesaditya3689
    @onesaditya3689 11 місяців тому +1

    Size = size * (ch -'0') sir pls explain this line..!!

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +1

      ASCII value of ‘0’ is = 48
      ASCII value of ‘1’ is = 49
      ASCII value of ‘2’ is = 50
      And so on…
      Suppose ch = ‘2’,
      Now when you do ch - ‘0’,
      It gives 50 - 48 = 2
      So if you see, from char ‘2’ , we are able to get integer 2 by doing ch - ‘0’
      Now, size = size * (ch -‘0’)
      Is done in order to find the size of resultant string if it’s repeated ch-‘0’ times.

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

      @@codestorywithMIK nice sir

  • @amitguptapc
    @amitguptapc 11 місяців тому +1

    bawaal 🔥content

  • @udaykumarchetla6205
    @udaykumarchetla6205 11 місяців тому +2

    Pls start gfg potd as well

    • @codestorywithMIK
      @codestorywithMIK  11 місяців тому +2

      I will plan that as well when i get back to India soon ❤️❤️

  • @user-nh2cg5uq9g
    @user-nh2cg5uq9g 11 місяців тому +1

    Input: s = "cbacdcbc"
    Output: "acdb"
    Bro yahan end me c kyun nii aya

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

    Bro I'm getting runtime error in this code:-- (where am I going wrong ?)
    class Solution {
    public:
    string removeDuplicateLetters(string s) {
    vector last(27,0);
    vector taken(27,false);
    for(int i=0; is[i] && last[ch-'a']>i)
    {
    taken[s[i]-'a'] = false;
    result.pop_back();
    }
    result.push_back(s[i]);
    taken[s[i]-'a'] = true;
    }
    return result;
    }
    };

  • @aadil4236
    @aadil4236 11 місяців тому +1

    Can we solve it with DP too? I mean, with recursion and memoization. I immediately thought of DP. Can't this also be solved with 01 Knapsack?

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

      I mean, DP(01 knapsack) and memoization.

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

      I think you can.
      For every character you have two options, when you reach end, keep storing the smallest lexicographically result.
      Good point 👌👍🏻

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

      @@codestorywithMIKWhen I tried it I was able to generate the smallest lexo string. I was seeing that in my console logs. But I was returning the wrong string everytime. Can I share the code, if you don't mind?

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

      @aadil4236 Sure please share. I will have a look by evening. ❤️

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

      @@codestorywithMIK Thank you man!

  • @taneyasoni
    @taneyasoni 11 місяців тому +1

    26/30

  • @yadav.nitin03
    @yadav.nitin03 11 місяців тому +1

    Yo