Katkat

Group Strings By Anagram Signature

OkxSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to normalize strings into canonical forms using hashing or frequency counting to identify anagrams efficiently.

Problem Statement

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Function Signature

def group_anagrams(strs: List[str]) -> List[List[str]]:

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Examples

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

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

Edge Cases

  • Empty list of strings.
  • Strings with length 0.
  • All strings are unique anagrams.
  • No strings are anagrams of each other.

Hints

Hint 1

Two strings are anagrams if and only if their sorted versions are identical.

Hint 2

Consider using a hash map where the key is the 'canonical' form of the string and the value is a list of original strings that map to that key.

Hint 3

Instead of sorting each string (O(K log K)), you can represent each string as a frequency array of 26 integers to achieve O(K) normalization time, where K is the string length.

Follow-up questions

  • How would your approach change if you were required to handle Unicode characters instead of just lowercase English letters?
  • What is the total time and space complexity of your solution in terms of N strings and K average string length?
  • If the input array is extremely large and does not fit in memory, how would you modify the approach to group anagrams?