LeetCode 49 Group Anagrams - Example and Complexity Analysis

Walkthrough and analysis

Let's do a dry run on strs = ["eat", "tea", "tan"] step by step.

For "eat": sort it → "aet". Map: {"aet": ["eat"]}.

For "tea": sort it → "aet". Key exists. Map: {"aet": ["eat", "tea"]}.

For "tan": sort it → "ant". New key. Map: {"aet": ["eat", "tea"], "ant": ["tan"]}.

Return the values: [["eat", "tea"], ["tan"]].

Sorting each string takes O(klogk)O(k \log k) where kk is string length. You do this for nn strings. That's O(nklogk)O(n \cdot k \log k) time.

The hash map stores all strings, so O(nk)O(n \cdot k) space.