Group Anagrams / Similar Words Together
viaGlassdoor
Problem: Given a list of strings, group the ones that are anagrams (or otherwise 'similar' by a defined rule, e.g., same set of characters) of each other together.
Constraints: Up to 10^4 strings, each up to ~100 characters.
Example: Input: ['eat','tea','tan','ate','nat','bat'] Output: [['eat','tea','ate'],['tan','nat'],['bat']]
Approach: For each string, compute a canonical key - either the sorted character sequence (e.g., 'eat' -> 'aet') or a character-frequency signature (26-length count array as a tuple/string) - and group strings sharing the same key using a hash map. Sorting-based keys cost O(k log k) per string of length k; frequency-signature keys cost O(k), giving overall O(nk) or O(nk log k) depending on the chosen key.
asked …