KatInterview

Cluster Words by Letter Inventory

StringsAuto-graded · 18 test cases
EasyAuto-gradedStringshash-mapstringsanagrams

Last updated

Tests whether you can use a canonical character-frequency key and a hash map to partition a list of strings into anagram groups in linear time.

Problem

You are given a list of lowercase words. Two words belong to the same cluster if one can be formed by rearranging the letters of the other — that is, they share exactly the same letters with exactly the same counts.

Write a function that partitions the input list into clusters and returns them. Every word must appear in exactly one cluster. Clusters may be returned in any order, and words within a cluster may also appear in any order.

Constraints

  • 0 <= len(words) <= 10^4
  • 0 <= len(words[i]) <= 100
  • Each words[i] contains only lowercase English letters (a–z).

Examples

Example 1

Input: cluster_by_letter_inventory(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])

Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Example 2

Input: cluster_by_letter_inventory([''])

Output: [['']]

Hints

Hint 1

Two words are in the same cluster when and only when their per-letter counts are identical — think about what makes a good dictionary key for that property.

Hint 2

A tuple of 26 integers, one count per letter a–z, is hashable and uniquely identifies a letter inventory. Build it in O(k) time per word by iterating once over the word's characters.

Hint 3

Use a dict that maps each inventory tuple to the list of words that share it. One pass over the input fills the dict; returning its values gives you the clusters.