Group anagrams | Leetcode #49

Поділитися
Вставка
  • Опубліковано 27 вер 2024
  • This video explains a very important interview problem which has already been asked in many big MNCs like microsoft,amazon,google,facebook etc. The problem says that given an array of strings, we need to group them such that strings in a group must be anagrams of each other. I have explained using 3 methods with code. It makes use of hashmap and hashmap of hashmap for optimal solution. CODE LINK is given below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    CODE LINK: gist.github.co...
    Check if 2 strings are anagram: • Check if two strings a...

КОМЕНТАРІ • 126

  • @aaryanchaturvedi3505
    @aaryanchaturvedi3505 4 роки тому +103

    Those two words "eat" "bat" hurts differently now, if you know what i mean !!!

  • @alaminhossain273
    @alaminhossain273 4 роки тому +25

    You can't explain more better than this, You deserve an award.

    • @techdose4u
      @techdose4u  4 роки тому +1

      Thanks :)

    • @Witch_Quiz
      @Witch_Quiz 8 місяців тому

      Very easy to understand and detailed

  • @syedyaser8753
    @syedyaser8753 3 роки тому +9

    The third approach can be further optimised by using integer as the hash key. As we have max 26 char, we can represent the hash as an integer. Iterate over the chars of the word and set the particular position bit in the integer and at the end use this integer as key/bucket in the map. Your map syntax would look something like this.
    Map

    • @harshitchoukse2602
      @harshitchoukse2602 3 роки тому

      you mean to say Map ???

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

      I think this won't work. Can you try with "abc" and "cc" will come under the same bucket.

    • @ayushbhagat9817
      @ayushbhagat9817 8 місяців тому

      i dont think we can do this because the word can have duplicate characters, so this will fail. Like how do we differentiate the word "cat" is different from "caat"

  • @deepalipatil4410
    @deepalipatil4410 4 роки тому +19

    Tons of thanks for such a precise explanation. No one can teach better than this. Hats off !!!!!

  • @voldemort576
    @voldemort576 3 роки тому +6

    Sir 3rd method time Complexity will be approximatly equal to 2nd method as to implement 3rd method we will use map, as we cannot use unordered_map inside unordered_map
    So time for third is Time - O(N * (M*log(N) + logN))

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

      You can create your own hasher for map vector pair

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

      exactly !! you cannot simplify it from 2nd one ,it becomes worse

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

    one of the most underrated channels!

  • @mohitsaran9193
    @mohitsaran9193 3 роки тому +3

    can you share the code of the third most optimised approach without sorting ??
    I cannot able to code it properly

  • @ksansudeen
    @ksansudeen 4 роки тому +4

    Hi, Thanks for this video.. i was stuck with below input ["",""]. the expected outcome is [["",""]].
    but in map since the empty string will be repeating the output im getting is [[""]]. i can handle for this edge case if string is empty, but pls advise if we can have better way.

  • @ShreyaSingh-vr9qi
    @ShreyaSingh-vr9qi 4 роки тому +2

    Second approach is awesome, we can also solve this problem using trie data structure

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

    why do you sort the stri[i] instead of the temp string? why do you prefer to modify the input instead of a temporary variable?

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

    I cannot believe this is a medium... graph problems I find are easier than this nonsense problem...

  • @ridimamittal4064
    @ridimamittal4064 4 роки тому +3

    THIS VIDEO IS JUST WOW, THANK YOUUU SOOO MUCH, I WAS NOT ABLE TO UNDERSTAND THIS AFTER HOURS I FIND IT AND IT IS SUCH A RELIEF, THANKS TON!!!!

  • @spetsnaz_2
    @spetsnaz_2 4 роки тому +3

    We can sort the temp string and not the original string so that the original string does not change if we have this constraint

  • @chandanchandak5194
    @chandanchandak5194 3 роки тому +1

    how abt Xoring each letter of a word and then will xor the words itsself, when xor results in 0 then they are anagram

  • @06-fahadkhan69
    @06-fahadkhan69 Рік тому

    Great explanation, this video is best among all the other videos on UA-cam because there are no shortcuts in it, which makes it understandable very easily

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

    class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
    strDic = {}

    for s in strs:
    arr = [0]*26
    for i in s:
    arr[ord(i)-97] += 1

    # As arr is an array and we can not use an array as a key of dictionary so make arr a tuple
    key = tuple(arr)
    if key not in strDic:
    strDic[key] = [s]
    else:
    strDic[key] += [s]

    res = []
    for key in strDic:
    res.append(strDic[key])

    return res

  • @yitingg7942
    @yitingg7942 3 роки тому +5

    Amazing!!!! Never really needed to see the code. Just by understanding the thought process I can implement the code. Thank you Sur!!
    Good evening lol!

  • @anshupatidar7928
    @anshupatidar7928 3 роки тому +5

    Please put the code of optimal approach in C++. I am not able to implement one map inside another map in C++.

  • @ShubhamMishra-mz4zw
    @ShubhamMishra-mz4zw Рік тому

    One of the best explanation for this problem. Thank you sir

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

    Very very very well explained brother! Thanks so much.

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

    can we take unordered_map
    basically unordered_map, in place of map

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

    if we add the ascii values of a word and use unordered_map it will be a single traversal and no need for sorting, correct me if I was wrong ;)

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

      But many words can have same ascii values sum but different letters in it

  • @mohammedsadiq1567
    @mohammedsadiq1567 4 роки тому +1

    Thank you bro!
    Glad you are doing the April challenge!

  • @alphagrowth3327
    @alphagrowth3327 3 роки тому +1

    Amazing explanation with so much clarity. Thanks man.

  • @DharmendraKumar-ut2bn
    @DharmendraKumar-ut2bn 2 роки тому

    if any charector comes twice like book then 3rd method will work ?

  • @paragroy5359
    @paragroy5359 3 роки тому

    Nice explanation sir..........thanks for making video it was really helpful

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

    unordered_map myMap;
    unordered_map myMap;
    these line show me error on leetcode

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

    Great explanatio, thank you so much! I've subscribed!

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

    really good explaination

  • @prathamjagga5597
    @prathamjagga5597 3 роки тому +1

    Awesome explanation. ThankYou Mam🐵

    • @techdose4u
      @techdose4u  3 роки тому +1

      It's sir 😂

    • @prathamjagga5597
      @prathamjagga5597 3 роки тому +1

      video bahr se hi itni achhi lagi bina dekhe hi comment kr diya😅

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

    Amazing explanation

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

    you make life simple

  • @shreyashjoshi4188
    @shreyashjoshi4188 4 роки тому +1

    Your videos are just awesome man!!!!

  • @3pleFly
    @3pleFly 2 роки тому

    thanks that was very clear and your diagram was very helpful to understand :)

  • @praveenchouhan6388
    @praveenchouhan6388 4 роки тому +1

    awesome explaination!!!!!!! thanks a lot

  • @anushsharma8645
    @anushsharma8645 4 роки тому +1

    where the october challlenge playlist sir pls upload it

    • @techdose4u
      @techdose4u  4 роки тому

      I will upload when I reach my workplace. Currently I am at home.

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

    Nice explanation!! But I'm not able to code for the most optimal approach..... How to add data in map within map...I'm not getting that

  • @gautamgarg5904
    @gautamgarg5904 3 роки тому +1

    bro your most optimal approach is taking more time than 2nd approach....

    • @techdose4u
      @techdose4u  3 роки тому +1

      Don't remeber. I will see.

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

    Can we use union find here?

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

    sir plz solve the problems in python

  • @prateekjain7623
    @prateekjain7623 3 роки тому +1

    Sir,can u make videos on recursion plzz sir

  • @voldemort576
    @voldemort576 3 роки тому +1

    What will be space complexity of 2nd and 3rd method ??

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

      In worst case,
      Key part of map: O(NK) -all are unique strings
      Value part : O(NK) -all N strings of K length

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

    Thanks a lot ...

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

    Can we take a sum of ASCII values and use them as "key" to hashmap?

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

      Just thought about this idea before watching the video, definitely you can!

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

      No, we can't. For, example, "ill" and "duh" have the same sum at the end.
      i is equal to 105
      l is equal to 108
      l is equal to 108
      321
      d is equal to 100
      u is equal to 117
      h is equal to 104
      321

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

    thank you sir!

  • @anjaan_ladka
    @anjaan_ladka 3 роки тому

    Thanku ❤️❤️❤️

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

    biliblibilblibilbliblib

  • @a.gcrazy555
    @a.gcrazy555 22 дні тому

    You are speaking like a robot in a monotonous tone please improve it .
    Btw explanation is good .

  • @saigopalraopeechara6912
    @saigopalraopeechara6912 3 роки тому +3

    how come time complexity is o(n*k) when we are using orderedmap in the last optimal approach?

  • @Weirdvloggertrue
    @Weirdvloggertrue 3 роки тому +3

    Sir, please provide the optimal solution in C++. Many of us are not able to implement that, please do that🙏

    • @techdose4u
      @techdose4u  3 роки тому

      Sure

    • @Weirdvloggertrue
      @Weirdvloggertrue 3 роки тому

      @@techdose4u Where have you posted that?

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

      It’s not possible to use unordered map for the optimal solution because unordered map doesn’t have hasher for . So either you create your own hasher or use regular map

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

    I was trying to solve this problem since yesterday night. But when I came to know about map, Its just a matter of a min to solve that one... Thank you TECH DOSE... God bless you...🙌🏻🙌🏻🙌🏻🙌🏻🙌🏻

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

    Your videos are of different level...thank you so much sir!

  • @sumanth664
    @sumanth664 4 роки тому +1

    I solved the problem but I'm failing at time complexity can you help me out?
    class Solution {
    public:
    vector groupAnagrams(vector& strs)
    {
    vector answers;
    bool flag = false;
    for (unsigned int i = 0; i < strs.size(); i++)
    {
    if (answers.size() == 0)
    {
    vector temp = { strs[i] };
    answers.push_back(temp);
    }
    else
    {
    flag = false;
    unsigned int j;
    for (j = 0; j < answers.size(); j++)
    {
    if (IsAnagram(answers[j][0],strs[i]))
    {
    flag = true;
    break;
    }
    }
    if (flag)
    answers[j].push_back(strs[i]);
    else
    {
    vector temp = { strs[i] };
    answers.push_back(temp);
    }
    }
    }
    return answers;
    }
    bool IsAnagram(string a, string b)
    {
    int const maxChar = 26;
    int count[maxChar] = { 0 };
    if (a.length() == b.length())
    {
    for (unsigned int i = 0; i < a.length(); i++)
    {
    count[a[i] - 'a']++;
    count[b[i] - 'a']--;
    }
    for (unsigned int i = 0; i < maxChar; i++)
    {
    if (count[i] > 0)
    return false;
    }
    return true;
    }
    return false;
    }
    };

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

    In 2nd approach , I used a map< vector, vector > , It gave an error. If anyone knows, please comment a simple explanation

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

    How to loop over within a single string in the vector of strings, to store their character frequency in the hashmap ? As we don't have another iterator to go through each character within a selected string

  • @MrDheeraj14
    @MrDheeraj14 4 роки тому +1

    Thanks Surya for the amazing explanation! :)
    Just a quick question, do we need to write Sorting algo in a coding interview? Or we can use just write Sort (which is taken care by the framework itself). I'm asking this because we've limited time and sorting is not the main focus here.

    • @techdose4u
      @techdose4u  4 роки тому +1

      No need to sort. If they ask them do otherwise not required.

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

      Bhul jane ka hunar....mujhko sikhate jao......
      Jaa rahe ho ..toh sabhi ashk mitaate jaao.....

  • @ayeshaadhikari6123
    @ayeshaadhikari6123 3 роки тому +1

    Thank you so much sir!!! I could code it by just watching 5 minutes of your video! Thanks a lot for explaining things in such a simplified way :) Keep growing!

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

    2nd approach
    class Solution {
    public:
    vector groupAnagrams(vector& strs) {
    vector ans;
    map mp;
    int n = strs.size();
    string temp;
    for(int i=0;isecond);
    }
    return ans;
    }
    };
    you are welcome !

  • @sheetaljain1771
    @sheetaljain1771 3 роки тому +1

    Please share optimal code in c++

  • @pocketfm2.o217
    @pocketfm2.o217 4 роки тому +1

    bhaiya is geeks for geeks sufficient for competitive programming

    • @techdose4u
      @techdose4u  4 роки тому +1

      Geeksforgeeks is sufficient for placements but for competitive programming, you will have to keep participating in contests. Geeks will provide materials but participation will help you improve you weak areas. So participate in codechef or codeforces.

    • @pocketfm2.o217
      @pocketfm2.o217 4 роки тому +3

      U are doing great job bhaiya♥️
      Love from Jharkhand

    • @techdose4u
      @techdose4u  4 роки тому +1

      Thanks :)

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

    I don't think we will be able to use unordered map in second approach. ordered_map operations will cost log(n)....increasing the time complexity to mnlog(n)

  • @openworld7585
    @openworld7585 4 роки тому +1

    very big Thanks for this video

  • @niteshkhetan9757
    @niteshkhetan9757 3 роки тому +1

    Mind blowing

  • @jreese9182
    @jreese9182 4 роки тому +1

    great solution man!

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

    why it isn't working with unordered map?

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

    what a solution! 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥

  • @fullysimplified7139
    @fullysimplified7139 3 роки тому

    Thanks for making this one

  • @offbeat.prince
    @offbeat.prince 2 роки тому

    Kindly check the time compexity:
    vector groupAnagrams(vector& strs) {
    int n = strs.size();
    map ump;
    for(int i =0;i < n; i++)
    {
    string s = strs[i];
    vector hsh(26,0);
    for(int j = 0; j < s.length(); j++)
    {
    hsh[s[j]-'a']++;
    }
    ump[hsh].push_back(s);

    }
    vector ans;
    for(auto it: ump)
    {
    auto temp = it.second;
    ans.push_back(temp);
    }
    return ans;
    }