From 77b57a8131edb6b33b53ca58f6578a16ab58ab2a Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 6 Sep 2022 16:52:42 +0800 Subject: [PATCH] vault backup: 2022-09-06 16:52:42 --- OJ notes/pages/Leetcode Group-Anagrams.md | 112 ++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 OJ notes/pages/Leetcode Group-Anagrams.md diff --git a/OJ notes/pages/Leetcode Group-Anagrams.md b/OJ notes/pages/Leetcode Group-Anagrams.md new file mode 100644 index 0000000..d859e21 --- /dev/null +++ b/OJ notes/pages/Leetcode Group-Anagrams.md @@ -0,0 +1,112 @@ +# Leetcode Group-Anagrams + +2022-09-06 16:46 + +> ##### Data structures: +> +> #DS #array #hash_table +> +> ##### Difficulty: +> +> #coding_problem #difficulty-medium +> +> ##### Additional tags: +> +> #leetcode +> +> ##### Revisions: +> +> N/A + +##### Links: + +- [Link to problem](https://leetcode.com/problems/group-anagrams/) + +--- + +### Problem + +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. + +#### Examples + +**Example 1:** + +**Input:** strs = ["eat","tea","tan","ate","nat","bat"] +**Output:** [["bat"],["nat","tan"],["ate","eat","tea"]] + +**Example 2:** + +**Input:** strs = [""] +**Output:** [[""]] + +**Example 3:** + +**Input:** strs = ["a"] +**Output:** [["a"]] + +#### Constraints + +- `1 <= strs.length <= 104` +- `0 <= strs[i].length <= 100` +- `strs[i]` consists of lowercase English letters. + +### Thoughts + +> [!summary] +> This is a #hash_table problem. + +This one can be solved simply using two-way hash tables, consisting two hash tables: +- ana2id: turn anagram into an id +- id2str: turn id into strings that has the anagrams + +The one problem is hashing vectors / arrays. Here we use +CPP-style initialization of C's array. + +> [!tip] +> CPP-style initialization of C array #tip +> ```cpp +> array ana = {}; +> ``` + +Note that vectors doesn't work in unordered hash maps, +unless we use custom hash functions. + +### Solution + +```cpp +class Solution { +public: + vector> groupAnagrams(vector &strs) { + // using to hash maps for 2-way conversion + map, int> ana2id; + // this one is the answer returned. + vector> id2str; + + int id = 0; + for (string str : strs) { + // Use aggregate initialization to default to 0. + array ana = {}; + + for (char s : str) { + ana[s - 'a']++; + } + + if (ana2id.find(ana) == ana2id.end()) { + // Not in the map. + ana2id[ana] = id; + id2str.push_back({}); + id2str.back().push_back(str); + id++; + } else { + // in the map, append it to id2str + id2str[ana2id[ana]].push_back(str); + } + } + + return id2str; + } +}; +``` \ No newline at end of file