Group Anagrams in Python

PythonServer Side ProgrammingProgramming

Suppose, we have a set of strings. We have to group anagram together. So if the ["eat", "tea", "tan", "ate", "nat", "bat"], then the groups are [["ate","eat","tea"],["nat","tan"],["bat"]]

To solve this, we will follow these steps −

  • Define res as map
  • for i in string array
    • x := x and join, sorted string of i
    • if x in result
      • insert i in result[x]
    • else result[x] := [i]
  • return values of res as list

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def groupAnagrams(self, strs):
      result = {}
      for i in strs:
         x = "".join(sorted(i))
         if x in result:
            result[x].append(i)
         else:
            result[x] = [i]
      return list(result.values())
ob1 = Solution()
print(ob1.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))

Input

["eat", "tea", "tan", "ate", "nat", "bat"]

Output

[["ate","eat","tea"],["nat","tan"],["bat"]]
raja
Published on 31-Jan-2020 06:01:59
Advertisements