SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Group Anagrams

Given an array of strings strs, group all anagrams together into sublists. You may return the answer in any order.

An anagram is a string that contains exactly the same characters as another string, but the order of the characters can be different.

Example 1:

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

Example 2:

Input: strs = [""] Output: [[""]]

Example 3:

Input: strs = ["a"] Output: [["a"]]

Recommended time and space complexity

You should aim for a solution with O(n * k * log(k)) time complexity and O(n * k) space complexity, where n is the number of strings and k is the maximum length of a string.


Hint 1

How can you determine if two strings are anagrams? What do all anagrams of the same string have in common?


Hint 2

Can you transform each string so that all anagrams produce the same result? Think about sorting characters.


Hint 3

Sorted characters of anagrams form the same string. Use this string as a key in a hash table to group anagrams.

This problem tests skills in working with strings, hash tables, and sorting. It develops skills in efficient text data processing, grouping elements by specific criteria, and algorithm optimization. Solving this problem improves understanding of hashing concepts and string manipulations.

Expected Input :

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

Expected Output

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