49. Group Anagrams

Medium

Problem:

Take an array of strings and group them by anagram.

Input: strs = ["eat","tea","tan","ate","nat","bat"] 
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

https://leetcode.com/problems/longest-palindromic-substring/arrow-up-right

What to learn:

sorted()

  • The sorted() function returns a sorted list of the specified iterable object.

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
for word in strs:
    print(sorted(word))
  • The sorted() function allows you to specify a key or function separately for sorting using the key= option.

c = ['ccc', 'aaaa', 'd', 'bb']
sorted(c, key=len)

a = ['cde', 'cfc', 'abc']
sorted(a, key=lambda s: (s[0], s[-1])) # sort by the first character, and then the last one
  • The sorted() function accepts a reverse parameter as an optional argument. Setting reverse = True sorts the iterable in the descending order.

Output

Resrouce: https://www.programiz.com/python-programming/methods/built-in/sortedarrow-up-right

sort()

sort() will sort the list in-place, mutating its indexes and returning None.

Solutions:

Another approach

The simplest way to determine anagrams is to compare them after sorting.

  1. Construct a dictionary with sorted strings as keys.

  2. Add anagrams that end up having the same key to the dictionary.

  3. Return only the values of the dictionary.

Last updated