question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
implement-magic-dictionary | [C++] Clean Code | c-clean-code-by-alexander-rjx5 | \nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n \n }\n \n /** Build a dictionary | alexander | NORMAL | 2017-09-10T03:19:54.684000+00:00 | 2017-09-10T03:19:54.684000+00:00 | 1,205 | false | ```\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n \n }\n \n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for (string w : dict) {\n words.insert(w);\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n for (int i = 0; i < word.size(); i++) {\n char wi = word[i];\n for (char ch = 'a'; ch <= 'z'; ch++) {\n if (ch == wi) continue;\n word[i] = ch;\n if (words.count(word)) return true;\n }\n word[i] = wi;\n }\n return false;\n }\nprivate:\n unordered_set<string> words;\n};\n``` | 7 | 1 | [] | 0 |
implement-magic-dictionary | Efficient Trie and Java 8 w/ Explanation | efficient-trie-and-java-8-w-explanation-xor6s | The implementation is a simple Trie, with the method relaxedSearch.\n\nrelaxedSearch searches for a word, with one deviation from a normal trie.\n\nIf there is | Cubicon | NORMAL | 2017-09-10T03:03:22.317000+00:00 | 2017-09-10T03:03:22.317000+00:00 | 3,974 | false | The implementation is a simple Trie, with the method relaxedSearch.\n\nrelaxedSearch searches for a word, with one deviation from a normal trie.\n\nIf there is a match with the current character, it proceeds as usual in that branch.\nBut for all the non matched characters, it still continues searching, by incrementing the changedTimes variable, which maintains how many times a character was changed in the word search from the root.\n\n\nAny search that involves changedTimes > 1, is immediately terminated by returning false as we are allowed to change only one character.\n\nThe solution is reached, when we find word in the trie and the changedTimes is exactly == 1.\n```\nclass MagicDictionary {\n\n Trie trie;\n public MagicDictionary() {\n trie = new Trie(256);\n }\n\n public void buildDict(String[] dict) {\n Arrays.stream(dict).forEach(s -> trie.insert(s));\n }\n\n public boolean search(String word) {\n return trie.relaxedSearch(word);\n }\n\n class Trie {\n private int R;\n private TrieNode root;\n\n public Trie(int R) {\n this.R = R;\n root = new TrieNode();\n }\n \n public boolean relaxedSearch(String word) {\n return relaxedSearch(root, word, 0);\n }\n\n private boolean relaxedSearch(TrieNode root, String word, int changedTimes) {\n if (root == null || (!root.isWord && word.isEmpty()) || changedTimes > 1) return false;\n if (root.isWord && word.isEmpty()) return changedTimes == 1;\n return Arrays.stream(root.next).anyMatch(nextNode -> relaxedSearch(nextNode, word.substring(1),\n root.next[word.charAt(0)] == nextNode ? changedTimes : changedTimes+1));\n }\n\n // Inserts a word into the trie.\n public void insert(String word) {\n insert(root, word);\n }\n\n private void insert(TrieNode root, String word) {\n if (word.isEmpty()) { root.isWord = true; return; }\n if (root.next[word.charAt(0)] == null) root.next[word.charAt(0)] = new TrieNode();\n insert(root.next[word.charAt(0)], word.substring(1));\n }\n\n private class TrieNode {\n private TrieNode[] next = new TrieNode[R];\n private boolean isWord;\n }\n\n }\n }\n``` | 7 | 2 | [] | 4 |
implement-magic-dictionary | 2 Solution Beginner Friendly Set and simple array using Zip (Python3) | 2-solution-beginner-friendly-set-and-sim-8daq | Approach\n Describe your approach to solving the problem. \n- 1. Array and Zip \n- 2. Set method\n\n# Complexity\n\n- Array and Zip\n - Time complexity: O(n | amitpandit03 | NORMAL | 2023-04-16T19:27:25.061918+00:00 | 2023-04-16T19:27:42.551740+00:00 | 342 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- 1. Array and Zip \n- 2. Set method\n\n# Complexity\n\n- Array and Zip\n - Time complexity: O(n * m)\n\n - Space complexity: O(n + m)\n- Set \n - Time complexity: O(26M) \n\n - Space complexity: O(n * m)\n\n# 1. Simple Array and zip method\n```\nclass MagicDictionary:\n\n def __init__(self):\n self.dict = []\n\n def buildDict(self, dictionary: List[str]) -> None:\n for ch in dictionary:\n self.dict.append((ch))\n \n\n def search(self, searchWord: str) -> bool:\n for word in self.dict:\n if len(word) == len(searchWord) and sum(c1 != c2 for c1, c2 in zip(word, searchWord)) == 1: return True\n return False\n```\n- explaination of if statement in Search()\n```\nfor word in self.dict:\n count = 0\n for c1, c2 in zip(word, searchWord): #if word is \'hello\' and searchWord is \'hhllo\', zip(word, searchWord) would produce ->\n if c1 != c2: #(\'h\', \'h\'), (\'e\', \'h\'), (\'l\', \'l\'), (\'l\', \'l\'), (\'o\', \'o\')\n count += 1\n\n if count == 1: return True\n else: return False\n\n\n```\n\n# 2 . Set method\n```\nclass MagicDictionary:\n\n def __init__(self):\n self.words = set()\n\n def buildDict(self, dictionary: List[str]) -> None:\n self.words = set(dictionary)\n\n def search(self, searchWord: str) -> bool:\n for i in range(len(searchWord)):\n for char in \'abcdefghijklmnopqrstuvwxyz\':\n if char == searchWord[i]:\n continue\n replaced_word = searchWord[:i] + char + searchWord[i + 1:]\n if replaced_word in self.words:\n return True\n return False\n```\n | 6 | 0 | ['Array', 'Hash Table', 'String', 'Design', 'Python3'] | 0 |
implement-magic-dictionary | My Java Solution with Trie and Backtracking Search | my-java-solution-with-trie-and-backtrack-vztk | Implement magic dictionary with two operations: buildDict and search. It\'s easy to come up with Trie to build a dict. The difficulty here for me is to implemen | xiaoxiao7 | NORMAL | 2020-02-29T09:45:55.200783+00:00 | 2020-02-29T11:03:57.496699+00:00 | 539 | false | Implement magic dictionary with two operations: `buildDict` and `search`. It\'s easy to come up with `Trie` to build a dict. The difficulty here for me is to implement the `search` operation.\nI use the backtracking way to find if there exists one word in the dict which has only one character different from the word I search.\n\nHere is the code. Hope it helps you think from a different way.\nI use a cnt to record the word\'s change times.\nThe key point is that if `cur.children[ch - \'a\']` is not null, we can search the next level without cnt + 1.\nOtherwise, we can search all other `cur.children` except the one that `cur.children[ch - \'a\']`.\nPlease point it out if anything is wrong.\n\n```\nclass MagicDictionary {\n\n TrieNode root;\n /** Initialize your data structure here. */\n public MagicDictionary() {\n root = new TrieNode();\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n for (String s : dict) {\n TrieNode cur = root;\n for (char ch : s.toCharArray()) {\n if (cur.children[ch - \'a\'] == null) cur.children[ch - \'a\'] = new TrieNode();\n cur = cur.children[ch - \'a\'];\n }\n cur.isWord = true;\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n return search(root, word.toCharArray(), 0, 0);\n }\n \n public boolean search(TrieNode cur, char[] word, int index, int cnt) {\n if (cur == null || cnt > 1) {\n return false;\n }\n if (index == word.length) {\n return cur.isWord && cnt == 1;\n }\n\n for (int i = 0; i < 26; ++i) {\n if (search(cur.children[i], word, index + 1, (word[index] - \'a\' != i) ? cnt + 1 : cnt)) {\n return true;\n }\n }\n return false;\n }\n \n class TrieNode {\n TrieNode[] children = new TrieNode[26];\n boolean isWord = false;\n }\n} | 6 | 0 | ['Backtracking', 'Trie', 'Java'] | 1 |
implement-magic-dictionary | C++ 0ms solution with Hashtable | c-0ms-solution-with-hashtable-by-jasperj-gega | \tclass MagicDictionary {\n\tpublic:\n\t\t/ Initialize your data structure here. */\n\t\tunordered_map> m;\n\t\tMagicDictionary() {\n\n\t\t}\n\n\t\t/ Build a di | jasperjoe | NORMAL | 2020-01-07T07:10:18.578013+00:00 | 2020-01-07T07:10:18.578045+00:00 | 416 | false | \tclass MagicDictionary {\n\tpublic:\n\t\t/** Initialize your data structure here. */\n\t\tunordered_map<int,vector<string>> m;\n\t\tMagicDictionary() {\n\n\t\t}\n\n\t\t/** Build a dictionary through a list of words */\n\t\tvoid buildDict(vector<string> dict) {\n\t\t\tfor(auto x:dict){\n\t\t\t\tm[x.size()].push_back(x);\n\t\t\t}\n\t\t}\n\n\t\t/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n\t\tbool search(string word) {\n\t\t\tint len=word.size();\n\t\t\tfor(auto v:m[len]){\n\t\t\t\tint count=0;\n\t\t\t\tfor(int i=0;i<v.size();i++){\n\t\t\t\t\tif(v[i]!=word[i]){\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\tif(count>1) continue;\n\t\t\t\t\tif(i==v.size()-1 && count==1) return true;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t};\n\n | 6 | 0 | ['Hash Table', 'C', 'C++'] | 2 |
implement-magic-dictionary | Python Simple Solution | python-simple-solution-by-yangshun-otxu | Since the input set is small and the character set is finite, it is acceptable to enumerate through all possible combinations and see if the new word exists in | yangshun | NORMAL | 2017-09-10T03:09:43.455000+00:00 | 2017-09-10T03:09:43.455000+00:00 | 1,042 | false | Since the input set is small and the character set is finite, it is acceptable to enumerate through all possible combinations and see if the new word exists in the dictionary and the time complexity for search is O(k^2) where k is the length of the word.\n\nFunnily enough, the comment in the skeleton for the `search` method already hints at using a "trie" but it's not needed to pass the contest.\n\n*- Yangshun*\n\n```\nclass MagicDictionary(object):\n\n def __init__(self):\n self.words = None\n\n def buildDict(self, dict):\n self.words = set(dict)\n\n def search(self, word):\n chars = set(word)\n for index, char in enumerate(word):\n for i in range(26):\n sub = chr(ord('a') + i)\n if sub == char:\n continue\n new_word = word[:index] + sub + word[index + 1:]\n if new_word in self.words:\n return True\n return False\n``` | 5 | 4 | [] | 1 |
implement-magic-dictionary | Two C++ solutions, Hash Table / Trie | two-c-solutions-hash-table-trie-by-zefen-htpl | Solution 1. Hash Table\n\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {}\n \n /** Build a dic | zefengsong | NORMAL | 2017-10-14T22:07:11.531000+00:00 | 2017-10-14T22:07:11.531000+00:00 | 669 | false | **Solution 1.** Hash Table\n```\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {}\n \n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for(auto x: dict) m[x.size()].push_back(x);\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n for(auto x: m[word.size()])\n if(oneEditDistance(x, word)) return true;\n return false;\n }\n \nprivate:\n unordered_map<int, vector<string>>m;\n bool oneEditDistance(string& a, string& b){\n int diff = 0;\n for(int i = 0; i < a.size() && diff <= 1; i++)\n if(a[i] != b[i]) diff++;\n return diff == 1;\n }\n};\n```\n***\n**Solution 2.** Trie\n```\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n root = new TrieNode();\n }\n \n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for(auto x: dict) buildTrie(x);\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n TrieNode* p = root;\n int diff = 0;\n for(int i = 0; i < word.size(); i++){\n char c = word[i];\n for(int j = 0; j < 26; j++){\n if(p->next[j] == p->next[c - 'a']) continue;\n if(p->next[j] && find(p->next[j], word.substr(i + 1))) return true;\n }\n if(p->next[c - 'a']) p = p->next[c - 'a'];\n }\n return false;\n }\n\nprivate:\n struct TrieNode{\n bool isWord;\n TrieNode* next[26];\n TrieNode():isWord(false){\n memset(next, NULL, sizeof(next));\n }\n };\n TrieNode* root;\n \n void buildTrie(string s){\n TrieNode* p = root;\n for(auto c: s){\n if(!p->next[c - 'a']) p->next[c - 'a'] = new TrieNode();\n p = p->next[c - 'a'];\n }\n p->isWord = true;\n }\n \n bool find(TrieNode* p, string s){\n for(auto c: s)\n if(p->next[c - 'a']) p = p->next[c - 'a'];\n else return false;\n return p->isWord;\n }\n};\n``` | 5 | 0 | ['Hash Table', 'Trie', 'C++'] | 2 |
implement-magic-dictionary | Very simple python 🐍 solution using set | very-simple-python-solution-using-set-by-1xhi | \nclass MagicDictionary:\n\n def __init__(self):\n self.myDict=set()\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in d | injysarhan | NORMAL | 2020-11-03T19:00:23.081720+00:00 | 2020-11-03T19:00:46.654215+00:00 | 292 | false | ```\nclass MagicDictionary:\n\n def __init__(self):\n self.myDict=set()\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n self.myDict.add(word)\n\n def search(self, searchWord: str) -> bool:\n \n for word in self.myDict:\n if len(word)==len(searchWord) and word!=searchWord:\n changes=0\n for l1,l2 in zip(searchWord,word):\n if l1!=l2:\n changes+=1\n if changes>1:\n break\n if changes==1:\n return True\n return False\n\n``` | 4 | 0 | ['Python', 'Python3'] | 1 |
implement-magic-dictionary | [Python] Solve this question in real interview with video explanation | python-solve-this-question-in-real-inter-qijq | My step by step approach to solve this question like in real interview with video explanation:\nhttps://youtu.be/zjnb7QUZMPQ\n\nIntuition: Hahsmap / Looping\n\n | iverson52000 | NORMAL | 2020-10-18T23:10:57.697302+00:00 | 2020-10-18T23:10:57.697333+00:00 | 322 | false | My step by step approach to solve this question like in real interview with video explanation:\nhttps://youtu.be/zjnb7QUZMPQ\n\nIntuition: Hahsmap / Looping\n\n**Code**\n```\nclass MagicDictionary:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.m = collections.defaultdict(list)\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n self.m[len(word)] += [word]\n \n def search(self, searchWord: str) -> bool:\n if len(searchWord) not in self.m: return False\n wordList = self.m[len(searchWord)]\n \n for word in wordList:\n cnt = 0\n for i in range(len(searchWord)):\n if searchWord[i] != word[i]: cnt += 1\n if cnt > 1: break\n if cnt == 1: return True \n return False\n```\n\nTime Complexity: O(m*n)\nSpace Complexity: O(m)\n\nFeel free to subscribe to my channel. More LeetCoding videos coming up! | 4 | 0 | ['Python'] | 0 |
implement-magic-dictionary | [C++] simple easy solution using Trie | c-simple-easy-solution-using-trie-by-sah-i08d | \nclass TrieNode {\npublic:\n TrieNode *children[26];\n bool is_terminal;\n \n TrieNode() {\n for(int i=0;i<26;++i) {\n children[i | sahilgoyals | NORMAL | 2020-07-09T09:51:12.165039+00:00 | 2020-07-09T09:51:12.165070+00:00 | 396 | false | ```\nclass TrieNode {\npublic:\n TrieNode *children[26];\n bool is_terminal;\n \n TrieNode() {\n for(int i=0;i<26;++i) {\n children[i]=NULL;\n }\n is_terminal=false;\n }\n};\n\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n TrieNode *root=new TrieNode();\n MagicDictionary() {\n \n }\n \n void insert(string s) {\n TrieNode *temp=root;\n for(char c: s) {\n int idx=c-\'a\';\n if(temp->children[idx]==NULL) {\n temp->children[idx]=new TrieNode();\n }\n temp=temp->children[idx];\n }\n temp->is_terminal=true;\n }\n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for(string s: dict) {\n insert(s);\n }\n }\n \n bool find(string s) {\n TrieNode *temp=root;\n for(char c: s) {\n int idx=c-\'a\';\n if(temp->children[idx]==NULL) {\n return false;\n }\n temp=temp->children[idx];\n }\n if(temp->is_terminal==true) {\n return true;\n }\n else {\n return false;\n }\n }\n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string s) {\n for(int i=0;i<s.length();++i){\n for(int j=0;j<26;++j) {\n char c=j+\'a\';\n if(c==s[i]) continue;\n swap(s[i],c);\n if(find(s)) {\n return true;\n }\n swap(s[i],c); //Backtrack\n }\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dict);\n * bool param_2 = obj->search(word);\n */\n``` | 4 | 0 | ['Backtracking', 'Trie', 'C++'] | 2 |
implement-magic-dictionary | Java Trie | java-trie-by-hobiter-uudf | \nclass MagicDictionary {\n public class Node{\n boolean isW;\n Node[] nodes;\n public Node() {\n nodes = new Node[26];\n | hobiter | NORMAL | 2020-05-24T02:24:38.240643+00:00 | 2020-05-24T02:24:38.240676+00:00 | 264 | false | ```\nclass MagicDictionary {\n public class Node{\n boolean isW;\n Node[] nodes;\n public Node() {\n nodes = new Node[26];\n isW = false;\n }\n }\n \n Node root;\n\n /** Initialize your data structure here. */\n public MagicDictionary() {\n root = new Node();\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n for (String w : dict) {\n Node curr = root;\n for (char c : w.toCharArray()) {\n if (curr.nodes[c - \'a\'] == null) {\n curr.nodes[c - \'a\'] = new Node();\n }\n curr = curr.nodes[c - \'a\'];\n }\n curr.isW = true;\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n char[] arr = word.toCharArray();\n for (int i = 0; i < arr.length; i++) {\n char c = arr[i];\n for (int j = 0; j < 26; j++) {\n if (j == (c - \'a\')) continue;\n arr[i] = (char) (\'a\' + j);\n if (isW(arr)) return true;\n }\n arr[i] = c;\n }\n return false;\n }\n \n public boolean isW(char[] arr) {\n Node curr = root;\n for (char c : arr) {\n if (curr.nodes[c - \'a\'] == null) {\n return false;\n }\n curr = curr.nodes[c - \'a\'];\n }\n return curr.isW;\n }\n}\n``` | 4 | 0 | [] | 1 |
implement-magic-dictionary | Simple Iterative Java Solution | simple-iterative-java-solution-by-soviet-lr7u | In order for a string to exist in a magic dictionary one character in the string must be modified. This means we can compare the incoming string against strings | sovietaced | NORMAL | 2017-09-10T06:28:43.158000+00:00 | 2017-09-10T06:28:43.158000+00:00 | 982 | false | In order for a string to exist in a magic dictionary one character in the string must be modified. This means we can compare the incoming string against strings in the dictionary and count how many characters do not match between the two. If only one character does not match the word exists in the magic dictionary. \n\nThere are some additional optimizations that we can make like only checking strings that have the same length as the input string and skipping over a word once more than one character has been found to not match.\n\n```\nclass MagicDictionary {\n private final List<String> words = new ArrayList<>();\n /** Initialize your data structure here. */\n public MagicDictionary() {\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n for (String s : dict) {\n words.add(s);\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n for (String s : words) {\n // Only check strings that are the same length\n if (word.length() != s.length()) {\n continue;\n }\n \n int numWrong = 0;\n \n // Compare each letter of each word and count how many letters are off.\n for (int i = 0; i < word.length(); i++) {\n char a = word.charAt(i);\n char b = s.charAt(i);\n \n if (a != b) {\n numWrong++;\n }\n \n // optimization\n if (numWrong > 1) {\n break;\n }\n }\n\n // If only one letter for each word is off, this is acceptable.\n if (numWrong == 1) {\n return true;\n } \n }\n return false;\n }\n}\n``` | 4 | 1 | [] | 2 |
implement-magic-dictionary | Trie DFS Solution C++ || Easy Solution | trie-dfs-solution-c-easy-solution-by-jar-fm8g | Code\ncpp []\n// TrieNode class\nclass TrieNode{\npublic:\n TrieNode* child[26];\n bool endWord;\n \n TrieNode(){\n endWord = false;\n\n | JArrazola | NORMAL | 2024-10-05T16:46:26.943688+00:00 | 2024-10-05T16:48:50.467273+00:00 | 224 | false | # Code\n```cpp []\n// TrieNode class\nclass TrieNode{\npublic:\n TrieNode* child[26];\n bool endWord;\n \n TrieNode(){\n endWord = false;\n\n for (size_t i = 0; i < 26; i++)\n child[i] = nullptr;\n }\n};\n\nclass MagicDictionary {\nprivate: \n TrieNode *root; // Trie root\n\n // Method to build the trie tree\n void buildWord(const string &s){\n TrieNode *curr = root;\n\n for(const char &c : s){\n if(!curr->child[c - \'a\']) curr->child[c - \'a\'] = new TrieNode();\n curr = curr->child[c - \'a\'];\n }\n curr->endWord = true;\n }\n \n // Take in count that you have to make a mandatory\n // modification in the string, so you HAVE to skip one \n // and only one character. You can use DFS to try all possible\n // ways.\n bool searchWithChange(const string &s, TrieNode *nd, const int idx, bool madeChange){\n if(!nd)\n return false;\n TrieNode *curr = nd;\n\n for (int i = idx; i < s.size(); i++){\n if(!madeChange){ // DFS\n for (int j = 0; j < 26; j++)\n if(curr->child[j] && j != s[i] - \'a\')\n if(searchWithChange(s, curr->child[j], i + 1, true)) // Recursive call\n return true;\n } \n // If the string is not complete return false, continue otherwise\n if(curr->child[s[i] - \'a\']) curr = curr->child[s[i] - \'a\'];\n else return false;\n }\n \n // Return true if we are at the end of the word and we made a change\n return curr->endWord && madeChange;\n }\n\npublic:\n MagicDictionary() {\n root = new TrieNode();\n }\n \n void buildDict(vector<string> dictionary) {\n for(const string &s : dictionary)\n buildWord(s);\n }\n \n bool search(string searchWord) {\n return searchWithChange(searchWord, root, 0, false);\n }\n};\n``` | 3 | 0 | ['String', 'Depth-First Search', 'Trie', 'C++'] | 1 |
implement-magic-dictionary | [Python 3] - Trie - Simple Solution | python-3-trie-simple-solution-by-dolong2-d640 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dolong2110 | NORMAL | 2023-07-20T16:26:39.734164+00:00 | 2024-03-12T02:14:18.525027+00:00 | 729 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N*K)$$ with N is the number of word and K is length of each word\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*K)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass TrieNode:\n\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.is_end = False\n\n\nclass MagicDictionary:\n\n def __init__(self):\n self.trie = TrieNode()\n \n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n cur = self.trie\n for ch in word:\n cur = cur.children[ch]\n cur.is_end = True\n \n\n def search(self, searchWord: str) -> bool:\n n = len(searchWord)\n def dfs(root: TrieNode, cnt: int, i: int) -> bool:\n if cnt > 1 or i == n: return cnt == 1 and root.is_end\n return any([dfs(root.children[c], cnt + int(c != searchWord[i]), i + 1) for c in root.children])\n \n return dfs(self.trie, 0, 0)\n# Your MagicDictionary object will be instantiated and called as such:\n# obj = MagicDictionary()\n# obj.buildDict(dictionary)\n# param_2 = obj.search(searchWord)\n``` | 3 | 0 | ['String', 'Trie', 'Python3'] | 1 |
implement-magic-dictionary | 676: Solution with step by step explanation | 676-solution-with-step-by-step-explanati-fx6f | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. init method\n 1. Create an empty dictionary to hold the words and t | Marlen09 | NORMAL | 2023-03-20T06:33:03.511296+00:00 | 2023-03-20T06:33:03.511331+00:00 | 726 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. __init__ method\n 1. Create an empty dictionary to hold the words and their replacements.\n 2. Store the dictionary in the class attribute self.dict.\n2. buildDict method\n 1. For each word in the dictionary argument:\n - For each index i in the range 0 to len(word):\n - Replace the character at index i with *.\n - Store the new string in a variable named replaced.\n - If replaced is already a key in the dictionary:\n - Append the original word to the list of words associated with the replaced key.\n - Otherwise, create a new key-value pair in the dictionary where the key is replaced and the value is a list containing word.\n 2. Store the updated dictionary in the class attribute self.dict.\n3. search method\n1. For each index i in the range 0 to len(searchWord):\n 1. Replace the character at index i with *.\n 2. Store the new string in a variable named replaced.\n 3. If replaced is a key in the dictionary:\n - Get the list of words associated with the replaced key.\n - For each word in the list:\n - If the word is not equal to searchWord and has the same length as searchWord:\n - Initialize a variable match to True.\n - For each index j in the range 0 to len(searchWord):\n - If the characters at index j in searchWord and word are not equal and the character at index j in replaced is not *, set match to False and break out of the loop.\n - If match is still True after the loop, return True.\n2. Return False if no matches were found.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass MagicDictionary:\n def __init__(self):\n self.dict = {}\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n for i in range(len(word)):\n replaced = word[:i] + \'*\' + word[i+1:]\n if replaced in self.dict:\n self.dict[replaced].append(word)\n else:\n self.dict[replaced] = [word]\n\n def search(self, searchWord: str) -> bool:\n for i in range(len(searchWord)):\n replaced = searchWord[:i] + \'*\' + searchWord[i+1:]\n if replaced in self.dict:\n words = self.dict[replaced]\n for word in words:\n if word != searchWord and len(word) == len(searchWord):\n match = True\n for j in range(len(searchWord)):\n if searchWord[j] != word[j] and replaced[j] != \'*\':\n match = False\n break\n if match:\n return True\n return False\n\n``` | 3 | 0 | ['Hash Table', 'String', 'Trie', 'Python', 'Python3'] | 0 |
implement-magic-dictionary | My fast Python solution | my-fast-python-solution-by-obose-d729 | Intuition\n Describe your first thoughts on how to solve this problem. \nMy first thoughts on how to solve this problem is to create a data structure that store | Obose | NORMAL | 2023-01-15T00:34:06.553925+00:00 | 2023-01-15T00:34:06.553967+00:00 | 469 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thoughts on how to solve this problem is to create a data structure that stores all the words in the dictionary. Then, when searching for a word, I will iterate through each word in the data structure and compare it to the search word. If the two words have a difference of only one character, I will return true.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach I will take is to first create a data structure to store the dictionary words, in this case a set. Then, I will implement the search function which will iterate through each word in the data structure and compare it to the search word. If the two words have a difference of only one character, the function will return true, otherwise it will return false.\n\n\n# Complexity\n- Time complexity: O(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass MagicDictionary:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.dic = set()\n\n def buildDict(self, dictionary: List[str]) -> None:\n self.dic = set(dictionary)\n\n def search(self, searchWord: str) -> bool:\n for word in self.dic:\n if len(word) == len(searchWord):\n diff = 0\n for i in range(len(word)):\n if word[i] != searchWord[i]:\n diff += 1\n if diff == 1:\n return True\n return False\n# Your MagicDictionary object will be instantiated and called as such:\n# obj = MagicDictionary()\n# obj.buildDict(dictionary)\n# param_2 = obj.search(searchWord)\n``` | 3 | 0 | ['Python3'] | 0 |
implement-magic-dictionary | [Java] | Trie | | java-trie-by-nepo_ian-szqr | \nclass MagicDictionary {\n\n private class Node {\n Node[] links;\n boolean isEnd;\n Node() {\n links = new Node[26];\n | nepo_ian | NORMAL | 2022-10-12T10:51:12.376371+00:00 | 2022-10-12T10:51:12.376415+00:00 | 409 | false | ```\nclass MagicDictionary {\n\n private class Node {\n Node[] links;\n boolean isEnd;\n Node() {\n links = new Node[26];\n isEnd = false;\n }\n }\n \n private Node root;\n public MagicDictionary() {\n root = new Node();\n }\n \n public void buildDict(String[] dictionary) {\n for (String str : dictionary) {\n insert(str);\n }\n }\n \n public boolean search(String searchWord) {\n return searchUtil(root, searchWord, 0, false);\n }\n \n private void insert(String str) {\n Node curr = root;\n for (char c : str.toCharArray()) {\n int ascii = c - \'a\';\n if (curr.links[ascii] == null) \n curr.links[ascii] = new Node();\n curr = curr.links[ascii];\n }\n curr.isEnd = true;\n }\n \n private boolean searchUtil(Node curr, String str, int i, boolean flag) {\n if (i == str.length()) \n return (curr.isEnd && i == str.length() && flag);\n \n boolean ans = false;\n int ascii = str.charAt(i) - \'a\';\n if (!flag) {\n for (int ii = 0; ii < 26; ii++) {\n if (ii == ascii || curr.links[ii] == null)\n continue;\n if (searchUtil(curr.links[ii], str, i + 1, true)) return true;\n }\n }\n if (curr.links[ascii] != null && searchUtil(curr.links[ascii], str, i + 1, flag))\n return true;\n return false;\n }\n}\n``` | 3 | 0 | ['Trie', 'Java'] | 0 |
implement-magic-dictionary | Easiest and understandable code | easiest-and-understandable-code-by-asppa-hyho | just change each word and check in trie\nTIME COMPLEXITY(n26logm)\n\n\nclass MagicDictionary {\n\n class Trie\n {\n boolean end;\n Trie node | asppanda | NORMAL | 2022-02-01T06:31:09.330423+00:00 | 2022-02-01T06:31:45.495128+00:00 | 400 | false | just change each word and check in trie\nTIME COMPLEXITY(n*26*logm)\n\n```\nclass MagicDictionary {\n\n class Trie\n {\n boolean end;\n Trie node[]=new Trie[26];\n Trie()\n {\n end=false;\n for(int i=0;i<26;i++)\n {\n node[i]=null;\n }\n }\n }\n \n static Trie Dict;\n public MagicDictionary() \n {\n Dict=new Trie();\n }\n \n public void buildDict(String[] dictionary) \n {\n int m=dictionary.length;\n for(int j=0;j<m;j++)\n {\n String s=dictionary[j];\n Trie ap=Dict;\n int n=s.length();\n for(int i=0;i<n;i++)\n {\n if(ap.node[s.charAt(i)-\'a\']==null)\n {\n Trie newnode=new Trie();\n ap.node[s.charAt(i)-\'a\']=newnode;\n }\n ap=ap.node[s.charAt(i)-\'a\'];\n }\n\n ap.end=true;\n }\n }\n public static boolean check(char ch[])\n {\n Trie check1=Dict;\n for(int i=0;i<ch.length;i++)\n {\n if(check1.node[ch[i]-\'a\']!=null)\n {\n check1=check1.node[ch[i]-\'a\'];\n }\n else\n {\n return false;\n }\n }\n if(check1.end==true)\n {\n return true;\n }\n return false;\n }\n public boolean search(String searchWord)\n {\n int n=searchWord.length();\n char ch[]=searchWord.toCharArray();\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<26;j++)\n {\n if(ch[i]==(j+97))\n {\n continue; \n }\n char op=ch[i];\n ch[i]=(char)(j+97);\n if(check(ch))\n {\n return true;\n }\n ch[i]=op;\n }\n \n }\n return false;\n \n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n```\n\n\n**PLS UPVOTE IF U LIKE THE SOLUTION** | 3 | 0 | ['Depth-First Search', 'Trie', 'Java'] | 1 |
implement-magic-dictionary | [Python3] Solution with using trie | python3-solution-with-using-trie-by-maos-onuh | \nclass MagicDictionary:\n def __init__(self):\n self.trie = {}\n self.end = \'end\'\n\n def buildDict(self, dictionary: List[str]) -> None: | maosipov11 | NORMAL | 2021-12-08T05:55:36.998771+00:00 | 2021-12-08T05:55:36.998797+00:00 | 251 | false | ```\nclass MagicDictionary:\n def __init__(self):\n self.trie = {}\n self.end = \'end\'\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n node = self.trie\n for c in word:\n if c not in node:\n node[c] = {}\n \n node = node[c]\n \n node[self.end] = True\n \n def _search_after_change(self, suffix, node):\n for c in suffix:\n if c not in node:\n return False\n \n node = node[c]\n \n if self.end not in node:\n return False\n \n return True\n \n def search(self, searchWord: str) -> bool:\n node = self.trie\n \n for idx in range(len(searchWord)):\n for key in node:\n if key != self.end and key != searchWord[idx]:\n suffix = searchWord[idx + 1:]\n if self._search_after_change(suffix, node[key]):\n return True\n \n # changing one character didn\'t give us anything\n if searchWord[idx] not in node:\n return False\n \n node = node[searchWord[idx]]\n \n return False\n``` | 3 | 0 | ['Array', 'Trie', 'Python3'] | 1 |
implement-magic-dictionary | C++ Easy to Understand Trie Solution | c-easy-to-understand-trie-solution-by-us-eh7c | \tstruct node {\n\t\t\tint count;\n\t\t\tint ew;\n\t\t\tnode ar[26];\n\t\t};\n\t\tnode getNode() {\n\t\t\tnode n=new node();\n\t\t\tn->ew=0; \n\t\t\tfor(int i=0 | user3408lm | NORMAL | 2021-07-29T13:03:25.855033+00:00 | 2021-07-29T13:03:25.855073+00:00 | 122 | false | \tstruct node {\n\t\t\tint count;\n\t\t\tint ew;\n\t\t\tnode* ar[26];\n\t\t};\n\t\tnode* getNode() {\n\t\t\tnode* n=new node();\n\t\t\tn->ew=0; \n\t\t\tfor(int i=0;i<26;i++) n->ar[i]=NULL;\n\t\t\tn->count=0;\n\t\t\treturn n;\n\t\t}\n\t\tvoid insert(node* root,string s) {\n\t\t\tnode* temp=root;\n\t\t\tfor(int i=0;i<s.size();i++) {\n\t\t\t\tint j=s[i]-\'a\';\n\t\t\t\tif(temp->ar[j]==NULL) temp->ar[j]=getNode();\n\t\t\t\ttemp=temp->ar[j]; temp->count++;\n\t\t\t}\n\t\t\ttemp->ew++;\n\t\t}\n\t\tbool find(node* root,string s) {\n\t\t\tnode* temp=root;\n\t\t\tfor(int i=0;i<s.size();i++) {\n\t\t\t\tint j=s[i]-\'a\';\n\t\t\t\tif(temp->ar[j]==NULL) return false;\n\t\t\t\ttemp=temp->ar[j]; \n\t\t\t}\n\t\t\tif(temp->ew>=1) return true;\n\t\t\treturn false;\n\t\t}\n\t\tnode* root;\n\t\tMagicDictionary() {\n\t\t\troot=getNode();\n\t\t}\n\n\t\tvoid buildDict(vector<string> dictionary) {\n\t\t\tfor(auto s: dictionary) insert(root,s);\n\t\t}\n\n\t\tbool search(string s) {\n\n\t\tfor(int i=0;i<s.size();i++) {\n\t\t\tfor(int j=0;j<26;j++) {\n\t\t\t\tchar c=(char)(j+\'a\');\n\t\t\t\tchar t=s[i];\n\t\t\t\tif(s[i]==c) continue;\n\t\t\t\ts[i]=c;\n\n\t\t\t\tif(find(root,s)) { return true; }\n\t\t\t\ts[i]=t;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t} | 3 | 0 | [] | 0 |
implement-magic-dictionary | Java || Trie || buildDict - O(dictionary.length*dictionary[i].length) || search - O(26*word.length) | java-trie-builddict-odictionarylengthdic-4x4d | public class Trie {\n\n\tprivate class Node {\n\n\t\tchar data;\n\t\tNode[] children;\n\t\tboolean isTerminal;\n\n\t\tpublic Node(char data, boolean isTerminal) | LegendaryCoder | NORMAL | 2021-02-04T08:48:58.835283+00:00 | 2021-02-04T08:48:58.835309+00:00 | 150 | false | public class Trie {\n\n\tprivate class Node {\n\n\t\tchar data;\n\t\tNode[] children;\n\t\tboolean isTerminal;\n\n\t\tpublic Node(char data, boolean isTerminal) {\n\t\t\tthis.data = data;\n\t\t\tthis.isTerminal = isTerminal;\n\t\t\tthis.children = new Node[26];\n\t\t}\n\n\t}\n\n\tprivate Node root;\n\n\t// O(1)\n\tpublic Trie() {\n\t\tthis.root = new Node(\'\\0\', false);\n\t}\n\n\t// O(word.length)\n\tpublic void addWord(String word) {\n\t\tNode curr = root;\n\t\tfor (char ch : word.toCharArray()) {\n\t\t\tNode temp = curr.children[ch - \'a\'];\n\t\t\tif (temp == null) {\n\t\t\t\ttemp = new Node(ch, false);\n\t\t\t\tcurr.children[ch - \'a\'] = temp;\n\t\t\t}\n\t\t\tcurr = temp;\n\t\t}\n\t\tcurr.isTerminal = true;\n\t}\n\n\t// O(word.length)\n\tpublic boolean searchWord(String word) {\n\t\treturn searchWord(root, word, 0, 0);\n\t}\n\n\t// O(word.length)\n\tprivate boolean searchWord(Node root, String word, int count, int vidx) {\n\n\t\tif (count == 2)\n\t\t\treturn false;\n\n\t\tif (vidx == word.length())\n\t\t\t\treturn (count == 1 && root.isTerminal) ? true : false;\n \n\t\tchar ch = word.charAt(vidx);\n\t\tfor (int i = 0; i < 26; i++) {\n\t\t\tif (root.children[i] != null) {\n\t\t\t\tchar temp = (char) (i + \'a\');\n\t\t\t\tint ncount = (ch == temp) ? count : count + 1;\n\t\t\t\tif (searchWord(root.children[i], word, ncount, vidx + 1))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n}\n\nclass MagicDictionary {\n\n\tTrie trie;\n\n\t// O(1)\n\tpublic MagicDictionary() {\n\t\ttrie = new Trie();\n\t}\n\n\t// O(dictionary.length*dictionary[i].length)\n\tpublic void buildDict(String[] dictionary) {\n\t\tfor (String word : dictionary)\n\t\t\ttrie.addWord(word);\n\t}\n\n\t// O(word.length)\n\tpublic boolean search(String searchWord) {\n\t\treturn trie.searchWord(searchWord);\n\t}\n}\n | 3 | 0 | [] | 1 |
implement-magic-dictionary | Python Trie Solution | python-trie-solution-by-realslimshady-i8cf | \nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.isWord = False\n\nclass Trie:\n def __ini | realslimshady | NORMAL | 2020-08-01T11:53:25.448640+00:00 | 2020-08-01T11:53:25.448688+00:00 | 121 | false | ```\nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.isWord = False\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n \n def insert(self,word):\n node = self.root\n for w in word:\n node = node.children[w]\n node.isWord = True\n \n def search(self,word,k,node):\n if not word:\n return k == 0 and node.isWord\n for r in node.children:\n if r == word[0]:\n if self.search(word[1:],k,node.children[r]):\n return True\n elif k == 1:\n if self.search(word[1:],k-1,node.children[r]):\n return True\n return False\n \nclass MagicDictionary:\n def __init__(self):\n self.t = Trie()\n\n def buildDict(self, dic: List[str]) -> None:\n for words in dic:\n self.t.insert(words)\n\n def search(self, word: str) -> bool:\n node = self.t.root\n return self.t.search(word,1,node)\n\n``` | 3 | 0 | [] | 0 |
implement-magic-dictionary | Python, modified search in Trie, O(AL) search | python-modified-search-in-trie-oal-searc-iohl | python\nclass TrieNode(object):\n def __init__(self):\n self.nxts = dict()\n self.isword = False\n \n def insert(self, word):\n | hungwei-andy | NORMAL | 2019-08-12T08:00:43.649031+00:00 | 2019-08-12T08:00:43.649061+00:00 | 398 | false | ```python\nclass TrieNode(object):\n def __init__(self):\n self.nxts = dict()\n self.isword = False\n \n def insert(self, word):\n cur = self\n for c in word:\n if c not in cur.nxts:\n cur.nxts[c] = TrieNode()\n cur = cur.nxts[c]\n cur.isword = True\n\n def search(self, word, i, skipn):\n if i == len(word):\n return self.isword and skipn == 1\n \n if skipn == 1:\n if word[i] not in self.nxts:\n return False\n return self.nxts[word[i]].search(word, i+1, skipn)\n \n for c in self.nxts:\n if self.nxts[c].search(word, i+1, skipn + int(c != word[i])):\n return True\n return False\n \nclass MagicDictionary(object):\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n \n\n def buildDict(self, dict):\n """\n Build a dictionary through a list of words\n :type dict: List[str]\n :rtype: None\n """\n self.trie = TrieNode()\n for word in dict:\n self.trie.insert(word)\n \n\n def search(self, word):\n """\n Returns if there is any word in the trie that equals to the given word after modifying exactly one character\n :type word: str\n :rtype: bool\n """\n return self.trie.search(word, 0, 0)\n\n\n# Your MagicDictionary object will be instantiated and called as such:\n# obj = MagicDictionary()\n# obj.buildDict(dict)\n# param_2 = obj.search(word)\n``` | 3 | 0 | [] | 0 |
implement-magic-dictionary | EASY TO UNDERSTAND || C++ | easy-to-understand-c-by-krish_kakadiya-gmb9 | C++\n\n# Code\n\nclass MagicDictionary {\npublic:\n vector<string> a;\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dict | krish_kakadiya | NORMAL | 2023-09-08T16:20:55.778795+00:00 | 2023-09-08T16:20:55.778815+00:00 | 175 | false | C++\n\n# Code\n```\nclass MagicDictionary {\npublic:\n vector<string> a;\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dictionary) {\n for(int i=0;i<dictionary.size();i++){\n a.push_back(dictionary[i]);\n }\n }\n \n bool search(string searchWord) {\n int f=0;\n for(int i=0;i<a.size();i++){\n string temp=a[i];\n if(a[i].size()!=searchWord.size()) continue;\n int curr=0;\n for(int j=0;j<temp.size();j++){\n if(temp[j]==searchWord[j]) curr++;\n }\n if(curr==temp.size()-1){\n f=1;\n break;\n }\n }\n\n return f==1;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 2 | 0 | ['C++'] | 0 |
implement-magic-dictionary | Solution | solution-by-deleted_user-du0s | C++ []\nclass MagicDictionary {\n public:\n void buildDict(vector<string> dictionary) {\n for (const string& word : dictionary)\n for (int i = 0; i < w | deleted_user | NORMAL | 2023-04-18T12:41:04.514127+00:00 | 2023-04-18T12:47:45.627641+00:00 | 682 | false | ```C++ []\nclass MagicDictionary {\n public:\n void buildDict(vector<string> dictionary) {\n for (const string& word : dictionary)\n for (int i = 0; i < word.length(); ++i) {\n const string replaced = getReplaced(word, i);\n dict[replaced] = dict.count(replaced) ? \'*\' : word[i];\n }\n }\n bool search(string searchWord) {\n for (int i = 0; i < searchWord.length(); ++i) {\n const string replaced = getReplaced(searchWord, i);\n if (dict.count(replaced) && dict[replaced] != searchWord[i])\n return true;\n }\n return false;\n }\n private:\n unordered_map<string, char> dict;\n\n string getReplaced(const string& s, int i) {\n return s.substr(0, i) + \'*\' + s.substr(i + 1);\n }\n};\n```\n\n```Python3 []\nclass MagicDictionary:\n\n def __init__(self):\n self.countDict = {}\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n if len(word) not in self.countDict: self.countDict[len(word)] = []\n self.countDict[len(word)].append(word)\n\n def isOneOff(self, word, searchWord) -> bool:\n numDiffs = 0\n for i in range(len(word)):\n if word[i] != searchWord[i]: numDiffs += 1\n if numDiffs > 1: return False\n return numDiffs == 1\n\n def search(self, searchWord: str) -> bool:\n if len(searchWord) not in self.countDict: return False\n candidates = self.countDict[len(searchWord)]\n for c in candidates:\n if self.isOneOff(c, searchWord): return True\n return False\n```\n\n```Java []\nclass MagicDictionary {\n private HashMap<Integer, ArrayList<String>> lenMap;\n public MagicDictionary() {\n lenMap = new HashMap<>();\n }\n public void buildDict(String[] dictionary) {\n lenMap.clear();\n for(String word: dictionary){\n if(!lenMap.containsKey(word.length())){\n lenMap.put(word.length(), new ArrayList<>());\n }\n lenMap.get(word.length()).add(word);\n }\n }\n public boolean search(String searchWord) {\n if(!lenMap.containsKey(searchWord.length())){\n return false;\n }\n ArrayList<String> arr = lenMap.get(searchWord.length());\n for(String word: arr){\n if(checkAlmostSame(searchWord, word)){\n return true;\n }\n }\n return false;\n }\n private boolean checkAlmostSame(String searchWord, String word){\n boolean foundDiff = false;\n for(int i = 0; i < word.length(); i++){\n if(word.charAt(i) != searchWord.charAt(i)){\n if(foundDiff == true){\n return false;\n } else {\n foundDiff = true;\n }\n }\n }\n return foundDiff;\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 0 |
implement-magic-dictionary | Easy c++ code using Trie Data Structure | easy-c-code-using-trie-data-structure-by-fn7v | \n\n# Code\n\nclass Trie{\n public:\n Trie* child[26];\n bool isEnd;\n Trie(){\n for(int i=0;i<26;i++){\n child[i]=NULL;\n | Shristha | NORMAL | 2023-01-13T16:58:22.559360+00:00 | 2023-01-13T16:58:22.559403+00:00 | 530 | false | \n\n# Code\n```\nclass Trie{\n public:\n Trie* child[26];\n bool isEnd;\n Trie(){\n for(int i=0;i<26;i++){\n child[i]=NULL;\n }\n isEnd=false; \n }\n};\nclass MagicDictionary {\npublic:\n Trie* root=new Trie();\n MagicDictionary() {\n \n } \n \n void buildDict(vector<string> dictionary) {\n \n for(int i=0;i<dictionary.size();i++){\n Trie* curr=root;\n string temp=dictionary[i];\n for(int j=0;j<temp.length();j++){\n int idx=temp[j]-97;\n if(curr->child[idx]==NULL){\n curr->child[idx]=new Trie();\n }\n curr=curr->child[idx];\n }\n curr->isEnd=true;\n }\n \n }\n bool check(string searchWord) {\n Trie* curr=root;\n for(int i=0;i<searchWord.length();i++){\n int idx=searchWord[i]-97;\n if(curr->child[idx]==NULL){\n return false;\n }\n curr=curr->child[idx];\n \n }\n \n return curr->isEnd;\n\n }\n \n \n bool search(string sword) {\n int n=sword.size();\n string word=sword;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<26;j++)\n {\n if(\'a\'+j==sword[i])\n continue;\n word[i]=\'a\'+j;\n if(check(word))\n return true;\n }\n word[i]=sword[i];\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 2 | 0 | ['C++'] | 1 |
implement-magic-dictionary | EASY TRIE SOLUTION C++ | easy-trie-solution-c-by-amangupta12207-r75e | Intuition\ninsert all the string in the trie \nIn search operation traverse the whole seachString, \nif trie does not contains that char then skip the curr char | Amangupta12207 | NORMAL | 2022-12-17T14:26:56.958133+00:00 | 2022-12-17T14:26:56.958160+00:00 | 1,042 | false | # Intuition\ninsert all the string in the trie \nIn search operation traverse the whole seachString, \nif trie does not contains that char then skip the curr character and check if u can find the remaining substring (implemented in helper function) return true else return false and if trie does contain that char then we have option to skip that character or not to skip that character so try by skipping this char if u find remaining substring by any other path, then return true else check further by moving to the next index\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nstruct Node {\n Node * links[26];\n bool flag = false;\n bool isContains(char ch){ // Node has ch or not\n return links[ch-\'a\'] != NULL;\n }\n void put (char ch, Node * node){\n links[ch-\'a\'] = node;\n }\n Node* get(char ch){\n return links[ch-\'a\'];\n }\n};\nclass MagicDictionary {\npublic:\n Node * root ;\n MagicDictionary() {\n root = new Node();\n }\n \n void buildDict(vector<string> dictionary) { // same as insert just wrap insert all the strings in dict\n for(auto word : dictionary){\n Node * node = root;\n int n = word.size();\n for(int i = 0;i<n;i++){\n if(!(node ->isContains(word[i]))){ // if node doesn\'t contain word[i]\n node->put(word[i],new Node());\n }\n node = node->get(word[i]); // move forward\n }\n node->flag = true; // word end\'s here mark flag as true \n }\n }\n \n bool search(string searchWord) {\n Node * node = root;\n int n = searchWord.size();\n for(int i = 0;i<n;i++){\n if(!node->isContains(searchWord[i])){ // if we don\'t find same char then skip this char and check if we found rem substring if yes return true else false\n string s = searchWord.substr(i+1);\n for(int j = 0;j<26;j++){\n Node * curr = node->get(j + \'a\');\n if(curr){\n if(SearchHelper(s,curr))\n return true;\n }\n }\n return false;\n }\n else { // if we find same char then we have option to skip and notskip so check by skpping this char and if we found rem substring return true else move to next character\n string s = searchWord.substr(i+1);\n int k = searchWord[i] - \'a\';\n for(int j = 0;j<26;j++){\n if(j == k) continue;\n Node * curr = node->get(j + \'a\');\n if(curr){\n if(SearchHelper(s,curr))\n return true;\n }\n }\n node = node->get(searchWord[i]);\n }\n }\n return false;\n }\n bool SearchHelper(string word, Node * node){ // normal search for same string we are callling this function after skipping a char so if we found remaining string i.e we need to change 1 char to convert a string into matching string\n int n = word.size();\n for(int i = 0;i<n;i++){\n if(!node ->isContains(word[i])){ // if node doesn\'t contain word[i]\n return false;\n }\n node = node->get(word[i]); // move forward\n }\n return node->flag; // if it contains all the char and flag is true at last it means word is here \n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 2 | 0 | ['Trie', 'C++'] | 0 |
implement-magic-dictionary | [C++] Trie || DFS || O(N) || Easy to Read | c-trie-dfs-on-easy-to-read-by-atman_2407-d64c | Explanation:\n\nHow to Implement Trie ?\n\nCheck this problem: 208 Implement Trie (Prefix Tree)Link\n\n\nContinue....\n\nPattern = Variation of Trie.\n\n- Inser | atman_2407 | NORMAL | 2022-03-04T05:44:27.290335+00:00 | 2022-03-04T05:44:27.290369+00:00 | 264 | false | **Explanation:**\n\nHow to Implement Trie ?\n\nCheck this problem: 208 Implement Trie (Prefix Tree)[Link](https://leetcode.com/problems/implement-trie-prefix-tree/)\n\n\nContinue....\n\nPattern = Variation of Trie.\n\n- Insert is same.\n\n- In search, we must perform one mismatch. Same word can not return true.\n\n Example.. "hello" -> "hello" return false.\n "hello" -> "hallo" return true.\n\nWe perform the Trie Traversal with DFS(for one mismatch).\n\nCheck the below code.\n\n\n```\n// Trie Node.\nstruct Node {\n\n Node* links[26];\n bool endOfWord = false;\n\n void put(char ch, Node* node) {\n links[ch-\'a\'] = node;\n }\n\n Node* get(char ch) {\n return links[ch-\'a\'];\n }\n\n bool contains(char ch) {\n return links[ch-\'a\'] != NULL;\n }\n\n void setEndOfWord() {\n endOfWord = true;\n }\n\n bool isEndOfWord() {\n return endOfWord;\n }\n};\n\n\n\nclass MagicDictionary {\n\npublic:\n\n MagicDictionary() {\n // Initialize the root node.\n root = new Node();\n }\n \n void buildDict(vector<string> dictionary) {\n\n // Add all the words into trie.\n for(string word: dictionary){\n insert(word);\n }\n }\n \n bool searchSupport(string s, int index, Node* node, bool allowedOnce) {\n \n // Base case. Found NULL, It can not be EndOfWord.\n if(node == NULL)\n return false;\n\n\n for(int i = index; i < s.size(); i++) {\n \n // allowedOnce is set then we try all characters for current s[i].\n if(allowedOnce) {\n\n for(char p = \'a\'; p <= \'z\'; p++) {\n \n // allowedOnce is depend, s[i] and p is same or not.\n // If same, then allowedOnce = true else false.\n if(searchSupport(s, i+1, node->get(p), s[i]==p)) {\n return true;\n }\n }\n\n // Try all characters but did not find the end of word. Return false.\n return false;\n }\n \n // allowedOnce = false, then node must contains s[i].\n if(!node->contains(s[i]))\n return false;\n\n // Move to next Node.\n node = node->get(s[i]);\n }\n \n // node is EndOfWord and allowedOnce == false(one mismatch) then we return true.\n if(node != NULL && !allowedOnce && node->isEndOfWord())\n return true;\n\n return false;\n }\n\n\n bool search(string searchWord) {\n return searchSupport(searchWord, 0, root, true);\n }\n\nprivate:\n\n Node* root;\n\n void insert(string word) {\n Node* node = root;\n for(char ch: word) {\n if(!node->contains(ch)) {\n node->put(ch, new Node());\n }\n node = node->get(ch);\n }\n node->setEndOfWord();\n }\n\n};\n\n```\n\n\n**Approach and Time Complexity:**\n\nN = number of words\nL = length of word\nk = 26\n\n1) Trie\nTime: O(N*L*K) = O(N) [L and K is constant]\nSpace: O(N*L) = O(N)\n | 2 | 0 | ['Depth-First Search', 'Trie', 'C'] | 0 |
implement-magic-dictionary | [C++] Trie Solution | c-trie-solution-by-logan-47-43ol | \nclass TrieNode {\npublic:\n TrieNode* children[26];\n bool isEnd;\n \n TrieNode() {\n for(int i=0; i < 26; i++) {\n children[i] | logan-47 | NORMAL | 2022-01-29T11:24:07.504756+00:00 | 2022-01-29T11:24:07.504781+00:00 | 305 | false | ```\nclass TrieNode {\npublic:\n TrieNode* children[26];\n bool isEnd;\n \n TrieNode() {\n for(int i=0; i < 26; i++) {\n children[i] = NULL;\n }\n isEnd = false;\n }\n};\n\n\nclass MagicDictionary {\npublic:\n \n TrieNode* head;\n MagicDictionary() {\n head = new TrieNode();\n }\n \n void buildDict(vector<string> dictionary) {\n for(auto word: dictionary) {\n insertWord(head, word);\n }\n }\n \n bool search(string searchWord) {\n return searchHelper(head, searchWord, 0, false);\n }\n \n bool searchHelper(TrieNode* head, string word, int i, bool isChanged) {\n if(i >= word.length()) return head->isEnd && isChanged;\n TrieNode* cur = head;\n int curInx = word[i] - \'a\';\n bool res = false;\n for(int j=0; j < 26; j++) {\n if(cur->children[j]) {\n if(j == curInx) {\n res = searchHelper(cur->children[j], word, i+1, isChanged);\n } else if(!isChanged) {\n res = searchHelper(cur->children[j], word, i+1, true);\n }\n }\n \n if(res) return true;\n \n }\n \n return false;\n \n }\n \n void insertWord(TrieNode* head, string word) {\n TrieNode* cur = head;\n for(auto ch: word) {\n if(cur->children[ch - \'a\'] == NULL) {\n cur->children[ch - \'a\'] = new TrieNode();\n }\n cur = cur->children[ch - \'a\'];\n }\n cur->isEnd = true;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 2 | 0 | ['Trie', 'C++'] | 2 |
implement-magic-dictionary | You guys know that the naive solution beats 100% here? | you-guys-know-that-the-naive-solution-be-6us3 | Just wanted to leave it here that for this question the absolute best solution (for the test cases presented) is a naive linear search:\n\n1. Save the dictionar | aalmos | NORMAL | 2021-11-29T08:56:09.390534+00:00 | 2021-11-29T08:56:09.390563+00:00 | 108 | false | Just wanted to leave it here that for this question the absolute best solution (for the test cases presented) is a naive linear search:\n\n1. Save the dictionary as is.\n2. Upon `Search` iterate over the dictionary and find any string that differs with a single character.\n\nThis is faster than any dictionary or trie approach. I also tried sorting the dictionary on string sizes and using binary search to find the segment that contains the words of the same size. It didn\'t help either.\n\nExample solution:\n\n```cpp\ninline bool OneCharDiff(const string& a, const string& b) {\n if (a.size() != b.size()) {\n return false;\n }\n int diff = 0;\n for (int i = 0; i < a.size() && diff <= 1; ++i) {\n diff += a[i] != b[i];\n }\n return diff == 1;\n}\n\nclass MagicDictionary {\n vector<string> d;\n \npublic:\n MagicDictionary() {}\n \n void buildDict(vector<string> dictionary) {\n d = move(dictionary);\n }\n \n bool search(string searchWord) {\n for (const string& w : d) {\n if (OneCharDiff(searchWord, w)) {\n return true;\n }\n }\n return false;\n }\n};\n``` | 2 | 0 | [] | 0 |
implement-magic-dictionary | [Python] Simple Trie + DFS Recursive Solution with Explanation | python-simple-trie-dfs-recursive-solutio-a0gg | For the Trie implementation I am not creating another TrieNode class instead using a dictionary as node and for wordEnd I am using "~" == True, if "~" is presen | Saksham003 | NORMAL | 2021-11-14T09:03:54.520376+00:00 | 2021-11-14T09:16:55.302877+00:00 | 237 | false | For the Trie implementation I am not creating another TrieNode class instead using a dictionary as node and for wordEnd I am using "~" == True, if "~" is present in dictionary then the word ends here, since dictionary only contains lower case english letters so it will not be a problem\n```\nclass MagicDictionary:\n def __init__(self):\n self.root = {}\n\n def buildDict(self, dictionary) -> None:\n for word in dictionary:\n curr = self.root #resetting curr to root\n for letter in word:\n if letter not in curr:\n curr[letter] = {}\n curr = curr[letter]\n curr["~"] = True #to signify word end\n\n def search(self, searchWord: str) -> bool:\n return self._search(searchWord, self.root, 0, 0)\n\t\t\n #I got the idea for this implementation from the knapsack pattern we use in dynamic programming\n\t#At every iteration we have two options either we choose the letter at index i or we skip it and choose any other letter from Trie marking diff as 1\n\t#we will try both options and keep the best result\n\t#but only if diff is 0 ,if diff is already 1 that means we have already changed a letter and now we can only choose letter at current index i, since we need exactly 1 different character\n\t\n def _search(self, word, node, diff, i):\n if i == len(word):\n if "~" in node and diff == 1: return True #since we need difference of exactly one character\n else: return False\n \n res = False\n if diff == 0: \n for letter in node:\n if letter == word[i] or letter == "~": continue #ignoring curr index and "~"\n res = res or self._search(word, node[letter], diff+1, i+1)\n \n if word[i] in node:\n res = res or self._search(word, node[word[i]], diff, i+1) # using "or" so that if any of the recursive calls returns true res will be true\n \n return res\n``` | 2 | 0 | ['Depth-First Search', 'Trie', 'Python', 'Python3'] | 0 |
implement-magic-dictionary | Python implementation using dictionary | python-implementation-using-dictionary-b-dn7r | Simple Python implementation using dictionary\n ```\n class MagicDictionary:\n def init(self):\n self.dict = {}\n self.word = set()\n def bu | maflint7 | NORMAL | 2021-08-31T19:47:51.593063+00:00 | 2021-08-31T19:50:20.641223+00:00 | 292 | false | Simple Python implementation using dictionary\n ```\n class MagicDictionary:\n def __init__(self):\n self.dict = {}\n self.word = set()\n def buildDict(self, dictionary: List[str]) -> None:\n # SC: O(n) # TC: O(nm)\n for word in dictionary:\n for i in range(len(word)):\n\t\t\t# building word templating to store as key, counting the number of template as value\n template = word[:i] + \'*\' + word[i+1:]\n self.dict[template] = 1 + self.dict.get(template,0)\n self.word.add(word)\n def search(self, searchWord: str) -> bool:\n # TC: O(m) SC: O(1)\n for i in range(len(searchWord)):\n template = searchWord[:i] + \'*\' + searchWord[i+1:]\n if template in self.dict:\n if searchWord not in self.word:\n return True\n else:\n\t\t\t\t# if the given word is in the dictionary, make sure there are more than 2 counts for the template\n if self.dict[template] >= 2:\n return True\n return False\n \n# Your MagicDictionary object will be instantiated and called as such:\n# obj = MagicDictionary()\n# obj.buildDict(dictionary)\n# param_2 = obj.search(searchWord) | 2 | 0 | ['Python', 'Python3'] | 0 |
implement-magic-dictionary | Java | Easy Solution | Set | Without Trie | java-easy-solution-set-without-trie-by-u-g8pb | \nclass MagicDictionary {\n\n /** Initialize your data structure here. */\n Set<String> set;\n public MagicDictionary() {\n set=new HashSet<>(); | user8540kj | NORMAL | 2021-05-04T12:59:51.582371+00:00 | 2021-05-04T12:59:51.582417+00:00 | 120 | false | ```\nclass MagicDictionary {\n\n /** Initialize your data structure here. */\n Set<String> set;\n public MagicDictionary() {\n set=new HashSet<>();\n }\n \n public void buildDict(String[] dictionary) {\n for(String s:dictionary) set.add(s);\n }\n \n public boolean search(String searchWord) {\n for(String s:set){\n if(canMake(s,searchWord)) return true;\n }\n return false;\n }\n public boolean canMake(String s,String sw){\n if(s.length()!=sw.length()) return false;\n int count=0;\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)!=sw.charAt(i)) count++;\n if(count>1) return false;\n }\n return count==1;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n``` | 2 | 0 | [] | 0 |
implement-magic-dictionary | Java || HashMap || buildDict - O(dictionary.length*dictionary[i].length) || search - O(word.length) | java-hashmap-builddict-odictionarylength-teca | class MagicDictionary {\n\n HashMap map;\n\n\t// O(1)\n\tpublic MagicDictionary() {\n\t\tmap = new HashMap();\n\t}\n\n\t\t// O(dictionary.length * dictionary | LegendaryCoder | NORMAL | 2021-02-04T09:12:00.560850+00:00 | 2021-02-04T09:12:00.560898+00:00 | 100 | false | class MagicDictionary {\n\n HashMap<String, Integer> map;\n\n\t// O(1)\n\tpublic MagicDictionary() {\n\t\tmap = new HashMap<String, Integer>();\n\t}\n\n\t\t// O(dictionary.length * dictionary[i].length)\n\t\tpublic void buildDict(String[] dictionary) {\n\t\t\tfor (String word : dictionary) {\n\t\t\t\tchar[] str = word.toCharArray();\n\t\t\t\tfor (int i = 0; i < str.length; i++) {\n\t\t\t\t\tchar temp = str[i];\n\t\t\t\t\tstr[i] = \'*\';\n\t\t\t\t\tString key = String.valueOf(str);\n\t\t\t\t\tmap.put(key, map.getOrDefault(key, 0) + 1);\n\t\t\t\t\tstr[i] = temp;\n\t\t\t\t}\n\t\t\t\tmap.put(word, 1);\n\t\t\t}\n\t\t}\n\n\t\t// O(searchWord.length)\n\t\tpublic boolean search(String searchWord) {\n\t\t\tchar[] word = searchWord.toCharArray();\n\t\t\tfor (int i = 0; i < word.length; i++) {\n\t\t\t\tchar temp = word[i];\n\t\t\t\tword[i] = \'*\';\n\t\t\t\tString key = String.valueOf(word);\n\t\t\t\tint count = map.getOrDefault(key, 0);\n\t\t\t\tif ((count >= 2) || (count == 1 && !map.containsKey(searchWord)))\n\t\t\t\t\treturn true;\n\t\t\t\tword[i] = temp;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n}\n\n | 2 | 0 | [] | 0 |
implement-magic-dictionary | JAVA || Trie || Clean code | java-trie-clean-code-by-igloo11-774c | \nclass MagicDictionary {\n class TrieNode {\n Map<Character, TrieNode> children;\n boolean endOfWord;\n public TrieNode() {\n | Igloo11 | NORMAL | 2021-01-12T04:29:12.596682+00:00 | 2021-01-12T04:29:12.596726+00:00 | 281 | false | ```\nclass MagicDictionary {\n class TrieNode {\n Map<Character, TrieNode> children;\n boolean endOfWord;\n public TrieNode() {\n children = new HashMap<>();\n endOfWord = false;\n }\n }\n \n //Insert by iteration\n public void insert(TrieNode root, String word) {\n TrieNode curr = root;\n \n for(char ch: word.toCharArray()) {\n TrieNode node = curr.children.get(ch);\n if(node == null) {\n node = new TrieNode();\n curr.children.put(ch, node);\n }\n curr = node;\n }\n \n curr.endOfWord = true;\n }\n \n //Search by iteration\n public boolean searchHelper(TrieNode root, String word) {\n TrieNode curr = root;\n \n for(char ch: word.toCharArray()) {\n TrieNode node = curr.children.get(ch);\n if(node == null) {\n return false;\n }\n curr = node;\n }\n \n return curr.endOfWord;\n }\n\n /** Initialize your data structure here. */\n public TrieNode root;\n public MagicDictionary() {\n root = new TrieNode();\n }\n \n public void buildDict(String[] dictionary) {\n for(String word: dictionary) {\n insert(root, word);\n }\n }\n \n public boolean search(String searchWord) {\n TrieNode curr = root;\n \n int count = 0;\n char[] word = searchWord.toCharArray();\n for(int i = 0; i < word.length; i++) {\n if(curr == null) {\n return false;\n }\n \n TrieNode node = curr.children.get(word[i]);\n char org = word[i];\n for(char ch: curr.children.keySet()) {\n if(ch == org) continue;\n \n word[i] = ch;\n if(searchHelper(root, new String(word))) {\n return true;\n }\n }\n word[i] = org;\n curr = node;\n }\n \n return false;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n``` | 2 | 0 | ['Trie', 'Java'] | 0 |
implement-magic-dictionary | Javascript Trie+DFS approach | javascript-triedfs-approach-by-yestrup-o2gi | \nfunction TrieNode(){\n this.children = new Map()\n this.endOfWord = false;\n}\n\nvar MagicDictionary = function() {\n this.root = new TrieNode()\n};\ | ratiboi | NORMAL | 2020-10-13T19:06:32.914851+00:00 | 2020-10-13T19:06:32.914895+00:00 | 160 | false | ```\nfunction TrieNode(){\n this.children = new Map()\n this.endOfWord = false;\n}\n\nvar MagicDictionary = function() {\n this.root = new TrieNode()\n};\n\nMagicDictionary.prototype.buildDict = function(dictionary) {\n for(let word of dictionary){\n let curr = this.root\n for(let letter of word){\n let map = curr.children\n if(!map.has(letter)) map.set(letter, new TrieNode())\n curr = map.get(letter)\n }\n curr.endOfWord = true\n }\n};\n\nMagicDictionary.prototype.search = function(searchWord){\n return dfs(this.root, searchWord, 0, 0)\n}\n\nfunction dfs(root, str, i, count){\n if(count>1) return false\n if(i==str.length) return count == 1 && root.endOfWord\n\t\n for(let [char, node] of root.children){\n let c = 0;\n if(char != str[i]) c = 1\n if(dfs(node, str, i+1, count+c)) return true;\n }\n return false\n}\n``` | 2 | 0 | ['Depth-First Search', 'JavaScript'] | 0 |
implement-magic-dictionary | Java - beats 100% - No HashMap/Trie - Easy to understand | java-beats-100-no-hashmaptrie-easy-to-un-givq | This solution doesn\'t use HashMap or Trie. \nbuildDict(String[] dict) complexity is O(1). \nsearch(String word) complexity is O(NK) where N is the total number | chere | NORMAL | 2020-07-02T03:45:23.909851+00:00 | 2020-07-02T03:45:23.909878+00:00 | 95 | false | This solution doesn\'t use HashMap or Trie. \n```buildDict(String[] dict)``` complexity is O(1). \n```search(String word)``` complexity is O(NK) where N is the total number of words in dictionary and K is the length of word to be searched.\n\n\n```\nclass MagicDictionary {\n\n String[] dictionary;\n /** Initialize your data structure here. */\n public MagicDictionary() {\n \n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n dictionary = dict;\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n for (String dictWord: dictionary) {\n if (dictWord.length() == word.length()) {\n int count = 0;\n for (int i=0; i< word.length(); i++) {\n if (word.charAt(i) != dictWord.charAt(i)) {\n count++;\n }\n if (count > 1) {\n break;\n }\n }\n if (count == 1) {\n return true;\n }\n }\n }\n return false;\n }\n}\n``` | 2 | 0 | [] | 0 |
implement-magic-dictionary | Python3 trie solution - Implement Magic Dictionary | python3-trie-solution-implement-magic-di-y2im | \nfrom collections import defaultdict\n\nclass Node:\n def __init__(self):\n self.child = defaultdict(Node)\n self.isEnd = False\n\nclass Magic | r0bertz | NORMAL | 2020-05-12T04:39:39.121163+00:00 | 2020-05-13T08:31:30.536050+00:00 | 276 | false | ```\nfrom collections import defaultdict\n\nclass Node:\n def __init__(self):\n self.child = defaultdict(Node)\n self.isEnd = False\n\nclass MagicDictionary:\n\n def __init__(self):\n self.trie = Node()\n \n def buildDict(self, words: List[str]) -> None:\n for w in words:\n n = self.trie\n for c in w:\n n = n.child[c]\n n.isEnd = True\n \n def searchWord(self, n: \'Node\', word: str) -> bool:\n for c in word:\n if c not in n.child:\n return False\n n = n.child[c]\n return n.isEnd\n \n\n def search(self, word: str) -> bool:\n n = self.trie\n for i, c in enumerate(word):\n if any(self.searchWord(n.child[k], word[i+1:]) for k in n.child if c != k):\n return True\n if c not in n.child:\n return False\n n = n.child[c]\n``` | 2 | 0 | ['Trie', 'Python', 'Python3'] | 0 |
implement-magic-dictionary | Python, DFS solution, beats 96% Time and 100% Space | python-dfs-solution-beats-96-time-and-10-qifx | The intuition behind this approach is to create a tree with nodes that hold characters. A path from the root node to a leaf node defines a string in the diction | andrewqho | NORMAL | 2019-08-12T05:40:30.792179+00:00 | 2019-08-12T05:43:15.117687+00:00 | 283 | false | The intuition behind this approach is to create a tree with nodes that hold characters. A path from the root node to a leaf node defines a string in the dictionary. \n\nWe define a structure called a letterNode that holds the current node\'s character value, the possible characters it can lead to, and whether it is a leaf node. \n\nOur MagicDictionary instance has one attribute, which is just the big daddy node that holds the start to all possible words. When we first build the dictionary, we iterate through all the words that are given to us, adding each string to a possible path. If the prefix of a string exists in Big Daddy\'s chlidren, then we continue down that path until the characters no longer match up. For example, if we first add hello, we get the tree:\n```\nbig_daddy -> \'h\' -> \'e\' -> \'l\' -> \'l\' -> \'o\'\n```\n\nwhere the node \'o\' is a leaf node. If we then have to add the words \'heklo\' and \'zaddy\', then we get the tree:\n\n```\n\t\t \'h\' -> \'e\' -> \'l\' -> \'l\' -> \'o\'\n\t / \\\nbig_daddy \'k\' -> \'l\' -> \'o\'\n \\\n\t \'z\' -> \'a\' -> \'d\' -> \'d\' -> \'y\'\n```\n\nWhen we search, we use a modified DFS algorithm. For each pass, we keep track of the current string, popping off the front value of the string and keep track of the number of characters modified to get to that node. For each node holding a char, we iterate through the child nodes, and if the child node and the current string have the same character in front, then we explore that node without decrementing the number of characters modified. If they don\'t have the same character in front, then we explore that node and decrement the number of characters modified. Our accept condition is if our current string is empty, the node we are at is a leaf node, and the number of characters to modify is equal to the number we needed to modify. Otherwise, we reject this path.\n\n```\nclass letterNode:\n def __init__(self, char):\n self.char = char\n self.children = []\n self.is_leaf = False\nclass MagicDictionary:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.big_daddy = letterNode(None)\n \n def addString(self, parent, curr_str):\n if len(curr_str) != 0:\n new_path = True\n for child in parent.children:\n if child.char == curr_str[0] and not child.is_leaf:\n self.addString(child, curr_str[1:])\n new_path = False\n break\n \n if new_path:\n new_node = letterNode(curr_str[0])\n parent.children.append(new_node)\n if len(curr_str) != 0:\n self.addString(new_node, curr_str[1:])\n \n else:\n parent.not_end = False\n \n def buildDict(self, dict):\n """\n Build a dictionary through a list of words\n """\n for word in dict:\n self.addString(self.big_daddy, word)\n \n\n def search(self, word):\n """\n Returns if there is any word in the trie that equals to the given word after modifying exactly one character\n """\n \n def dfs(parent, curr_str, chars_left_to_modify):\n if len(curr_str) == 0:\n if chars_left_to_modify == 0:\n if len(parent.children) == 0:\n return True\n else:\n return False\n else:\n return False\n \n for child in parent.children:\n if child.char == curr_str[0]:\n if dfs(child, curr_str[1:], chars_left_to_modify):\n return True\n else:\n if chars_left_to_modify > 0:\n if dfs(child, curr_str[1:], chars_left_to_modify-1):\n return True\n \n return False\n \n return dfs(self.big_daddy, word, 1)\n``` | 2 | 0 | [] | 2 |
implement-magic-dictionary | Python - really easy to understand (Explanations) | python-really-easy-to-understand-explana-ywnh | Instead of using a Trie, we can make a dictionary with the lengths of the words as the key and the list of all the words with the length as values, something li | crazyphotonzz | NORMAL | 2018-07-18T17:10:45.290275+00:00 | 2018-07-18T17:10:45.290275+00:00 | 207 | false | Instead of using a Trie, we can make a dictionary with the lengths of the words as the key and the list of all the words with the length as values, something like this:\n```defaultdict(<type \'list\'>, {8: [u\'leetcode\'], 5: [u\'hello\', u\'hallo\']})```\n\nNow, we simply have to go through each word in the dictionary, whise length matches with the incoming word and see the number of same characters, if that is equal to the length - 1, then we get our answer. \nNOTE: We cannot use a set here, because the order of the words matter. Hence, need to use a list only.\nThe worst case time complexity will be O(n*|word|), but that will rarely occur, since we are negating all the words with the different lengths in a single strike.\nThe code is as below:\n\n```from collections import defaultdict\n\nclass MagicDictionary(object):\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.d = defaultdict(list)\n\n def buildDict(self, dict):\n """\n Build a dictionary through a list of words\n :type dict: List[str]\n :rtype: void\n """\n for word in dict:\n length = len(word)\n self.d[length].append(word)\n print(self.d)\n\n def search(self, word):\n """\n Returns if there is any word in the trie that equals to the given word after modifying exactly one character\n :type word: str\n :rtype: bool\n """\n lenn = len(word)\n \n if lenn not in self.d:\n return False\n \n for w in self.d[lenn]:\n count = 0\n i = 0\n while i< lenn:\n if w[i] == word[i]:\n count += 1\n i += 1\n if count == lenn-1:\n return True\n return False\n```\n | 2 | 0 | [] | 0 |
implement-magic-dictionary | C++ Trie Solution avoid memory leak | c-trie-solution-avoid-memory-leak-by-qin-jvkb | Many have posted C++/Java Trie solution, for Java, we do not need to consider possible memory leak, but for C++, a lot of people use pointers without releasing | qinzhou | NORMAL | 2018-01-12T22:15:46.265000+00:00 | 2018-01-12T22:15:46.265000+00:00 | 352 | false | Many have posted C++/Java Trie solution, for Java, we do not need to consider possible memory leak, but for C++, a lot of people use pointers without releasing them (or not completely release them after terminates), here I post my Trie solution with *shared_ptr*, a smart pointer which guarantees completely memory recycle.\n```\nclass TrieNode {\npublic:\n vector<shared_ptr<TrieNode>> next;\n bool is_word;\n TrieNode() {\n next = vector<shared_ptr<TrieNode>>(26);\n is_word = false;\n }\n};\nclass MagicDictionary {\nprivate:\n shared_ptr<TrieNode> root;\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n root = make_shared<TrieNode>();\n }\n\n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for (string& str : dict) {\n shared_ptr<TrieNode> cur = root;\n for (char& c : str) {\n if (cur->next[c - 'a'] == nullptr) {\n cur->next[c - 'a'] = make_shared<TrieNode>();\n }\n cur = cur->next[c - 'a'];\n }\n cur->is_word = true;\n }\n }\n\n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n for (int i = 0; i < word.size(); i++) {\n for (char c = 'a'; c <= 'z'; c++) {\n if (word[i] == c) continue;\n char temp = word[i];\n word[i] = c;\n if (searchTrie(word)) return true;\n word[i] = temp;\n }\n }\n return false;\n }\n\n bool searchTrie(string& word) {\n shared_ptr<TrieNode> cur = root;\n for (char& c : word) {\n if (cur->next[c - 'a'] == nullptr) return false;\n cur = cur->next[c - 'a'];\n }\n return cur->is_word;\n }\n};\n``` | 2 | 0 | [] | 0 |
implement-magic-dictionary | Java implementation using Trie | java-implementation-using-trie-by-marvin-sjul | The basic idea is:\n\nFirst, insert the dictionary list into the Trie;\n\nSecond, for each given word, scan character by character. For each character, try modi | marvinbai | NORMAL | 2017-09-20T19:01:55.406000+00:00 | 2017-09-20T19:01:55.406000+00:00 | 709 | false | The basic idea is:\n\nFirst, insert the dictionary list into the Trie;\n\nSecond, for each given word, scan character by character. For each character, try modify it and then call the search method in Trie. If trie.search() returns true then return true. If not then see if the Trie has exactly this character, if yes then keep going, if not return false.\n\nFinally, if reaches the end of the word return false. This means the dictionary has exactly this word. But modifying any of the character cannot fit in the dictionary.\n\nHere is my Java solution using Trie:\n```\nclass MagicDictionary {\n private Trie trie;\n \n /** Initialize your data structure here. */\n public MagicDictionary() {\n trie = new Trie();\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n for(String word : dict) {\n trie.insert(word);\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n TrieNode curr = trie.root;\n int k = 0;\n while(curr != null) {\n if(k == word.length()) {\n //System.out.println(1);\n return false;\n }\n char c = word.charAt(k);\n int index = c - 'a';\n for(int i = 0; i < 26; i++) {\n if(i == index) continue;\n if(curr.children[i] != null && searchHelper(word, k+1, curr.children[i])) {\n return true;\n }\n }\n k++;\n curr = curr.children[index];\n }\n return false;\n }\n \n public boolean searchHelper(String word, int k, TrieNode node) {\n if(k == word.length()) return node.isWord;\n char c = word.charAt(k);\n int index = c - 'a';\n if(node.children[index] == null) return false;\n return searchHelper(word, k + 1, node.children[index]);\n }\n}\n```\nThe Trie implementation is here:\n```\nclass TrieNode {\n public char val;\n public TrieNode[] children = new TrieNode[26];\n public boolean isWord;\n public TrieNode() {};\n public TrieNode(char c) {\n this.val = c;\n }\n}\n\nclass Trie {\n public TrieNode root;\n public Trie() {\n this.root = new TrieNode(' ');\n }\n public void insert(String word) {\n TrieNode curr = root;\n for(int i = 0; i < word.length(); i++) {\n char c = word.charAt(i);\n int index = c - 'a';\n if(curr.children[index] == null) {\n curr.children[index] = new TrieNode(c);\n }\n curr = curr.children[index];\n }\n curr.isWord = true;\n return;\n }\n}\n``` | 2 | 0 | [] | 1 |
implement-magic-dictionary | Simple JavaScript Solution | simple-javascript-solution-by-dnshi-63gz | js\n/**\n * Initialize your data structure here.\n */\nvar MagicDictionary = function() {\n this.table = {}\n};\n\n/**\n * Build a dictionary through a list | dnshi | NORMAL | 2017-09-25T00:04:36.977000+00:00 | 2017-09-25T00:04:36.977000+00:00 | 306 | false | ```js\n/**\n * Initialize your data structure here.\n */\nvar MagicDictionary = function() {\n this.table = {}\n};\n\n/**\n * Build a dictionary through a list of words \n * @param {string[]} dict\n * @return {void}\n */\nMagicDictionary.prototype.buildDict = function(dict) {\n for (let word of dict) {\n this.table[word.length] = (this.table[word.length] || []).concat(word)\n }\n};\n\n/**\n * Returns if there is any word in the trie that equals to the given word after modifying exactly one character \n * @param {string} word\n * @return {boolean}\n */\nMagicDictionary.prototype.search = function(word) {\n return !!this.table[word.length] && this.table[word.length].some((w) => {\n let isModified = false\n\n for (let i = 0; i < word.length; ++i) {\n if (word[i] !== w[i]) {\n if (isModified) {\n return false\n } else {\n isModified = true\n }\n }\n }\n return isModified\n })\n};\n``` | 2 | 0 | [] | 0 |
implement-magic-dictionary | ✅ Trie + DFS | ✅ Easy Code | trie-dfs-easy-code-by-sajal0701-4v6x | IntuitionThe problem requires us to implement a dictionary where we can check if modifying exactly one character in a search word can match any word in the dict | Sajal0701 | NORMAL | 2025-02-26T14:17:53.012629+00:00 | 2025-02-26T14:17:53.012629+00:00 | 121 | false | # Intuition
The problem requires us to implement a dictionary where we can check if modifying exactly one character in a search word can match any word in the dictionary. A **Trie** (Prefix Tree) is an ideal data structure for this because it allows us to efficiently store words and perform character-based searches.
# Approach
1. **Trie Construction:**
- We create a `MagicDictionary` class with a root Trie node.
- Each node contains an array of pointers to child nodes (representing 26 lowercase English letters) and a boolean `end` to mark word completion.
- The `buildDict` function inserts each word into the Trie.
2. **Search with One Modification:**
- The `search` function performs a **DFS traversal** over the Trie.
- At each step, we either:
- Follow the exact character match (if it's present).
- Try replacing it with any other letter (only if no replacement has been made before).
- If we reach the end of a word in the Trie with exactly one change, we return `true`.
# Complexity
- **Time Complexity:**
- **Insertion:** $$O(n \cdot k)$$, where $$n$$ is the number of words and $$k$$ is the average word length.
- **Search:** $$O(k \cdot 26)$$, since for each character in the search word, we iterate over at most 26 possibilities.
- **Space Complexity:** $$O(n \cdot k)$$ to store all words in the Trie.
# Code
```cpp
struct Node {
Node* links[26] = {NULL};
bool end = false;
bool contain(char ch) {
return links[ch - 'a'] != NULL;
}
void put(char ch, Node* node) {
links[ch - 'a'] = node;
}
Node* get(char ch) {
return links[ch - 'a'];
}
bool isEnd() {
return end;
}
void setEnd() {
end = true;
}
};
class MagicDictionary {
public:
Node* root;
MagicDictionary() {
root = new Node();
}
void insert(string& s) {
Node* node = root;
for (char c : s) {
if (!node->contain(c)) {
node->put(c, new Node());
}
node = node->get(c);
}
node->setEnd();
}
void buildDict(vector<string> dictionary) {
for (auto& word : dictionary) {
insert(word);
}
}
bool dfs(Node* node, string& word, int index, bool changed) {
if (!node) return false;
if (index == word.size()) return changed && node->isEnd();
char curr = word[index];
for (char c = 'a'; c <= 'z'; c++) {
if (node->contain(c)) {
if (c == curr) {
if (dfs(node->get(c), word, index + 1, changed)) {
return true;
}
} else if (!changed) {
if (dfs(node->get(c), word, index + 1, true)) {
return true;
}
}
}
}
return false;
}
bool search(string searchWord) {
return dfs(root, searchWord, 0, false);
}
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dictionary);
* bool param_2 = obj->search(searchWord);
*/
```
| 1 | 0 | ['Depth-First Search', 'Trie', 'C++'] | 0 |
implement-magic-dictionary | ✅Easy and Simple Solution With Explanation ✅ Clean Code ✅ Best Solution | easy-and-simple-solution-with-explanatio-fzed | \nGuy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\nFo | ayushluthra62 | NORMAL | 2024-08-11T18:29:08.445758+00:00 | 2024-08-11T18:29:08.445792+00:00 | 198 | false | \n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]**\n\n# Complexity\n- Time complexity:\nbuildDict Function : O(N)\n Search Function : O(N * 26)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass MagicDictionary {\npublic:\nunordered_map<string,int>mapping;\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dictionary) {\n for(auto i : dictionary) mapping[i]++;\n }\n \n bool search(string searchWord) {\n \n \n \n\n\n // check for all the possibilites \n // iterate over the string and put all 26 char on currentPosition and check if it is present or not \n // if not just put the original curr back check for rest of string\n for(int j=0;j<searchWord.length();j++){\n char currChar = searchWord[j];\n\n for(int i=0;i<26;i++){\n char newChar = (char)(\'a\'+i);\n\n searchWord[j] =newChar;\n\n if(currChar != newChar && mapping.find(searchWord) != mapping.end()) return true;\n }\n searchWord[j] = currChar;\n\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n```\n\n\n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]** | 1 | 0 | ['Hash Table', 'String', 'Depth-First Search', 'Design', 'Trie', 'C++'] | 0 |
implement-magic-dictionary | Beats 98%, easy to understand... simple approach | beats-98-easy-to-understand-simple-appro-zfw0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | manyaagargg | NORMAL | 2024-07-26T02:03:51.607121+00:00 | 2024-07-26T02:03:51.607145+00:00 | 116 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass MagicDictionary {\n vector<string> vec;\npublic:\n MagicDictionary() {\n vector<string> vec;\n }\n \n void buildDict(vector<string> dictionary) {\n vec.assign(dictionary.begin(), dictionary.end());\n }\n \n bool search(string searchWord) {\n // return true;\n bool flag= false;\n for(int i=0; i<vec.size(); i++){\n if(searchWord.size() != vec[i].size()) continue;\n else{\n int cnt=0;\n for(int j=0; j<vec[i].size(); j++){\n if(searchWord[j]!=vec[i][j]) cnt++;\n }\n if(cnt==1) return true;\n }\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['Array', 'Hash Table', 'String', 'Depth-First Search', 'Design', 'Trie', 'C++'] | 0 |
implement-magic-dictionary | Java 8 solution | using Map | Easy to understand | java-8-solution-using-map-easy-to-unders-i5rb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | bhargava2123 | NORMAL | 2024-07-06T10:07:24.485264+00:00 | 2024-07-06T10:07:24.485297+00:00 | 32 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass MagicDictionary {\n\n Map<Integer, List<String>> map;\n \n public MagicDictionary() {\n }\n \n public void buildDict(String[] dictionary) {\n map = Arrays.stream(dictionary).collect(Collectors.groupingBy(String::length));\n }\n\n public boolean search(String searchWord) {\n var length = searchWord.length();\n if (!map.containsKey(length)) {\n return false;\n }\n var list = map.get(length);\n\n for (var str : list) {\n var start = 0;\n var end = str.length() - 1;\n var count = 0;\n while (start <= end) {\n if (count > 1) {\n break;\n }\n if (str.charAt(start) != searchWord.charAt(start)) {\n count++;\n }\n if (end != start && str.charAt(end) != searchWord.charAt(end)) {\n count++;\n }\n start++;\n end--;\n }\n if (count == 1) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n``` | 1 | 0 | ['Java'] | 0 |
implement-magic-dictionary | Just a dictionary | just-a-dictionary-by-pawan481992-374i | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\nM is nu | pawan481992 | NORMAL | 2023-12-29T14:01:15.982187+00:00 | 2023-12-29T14:01:15.982216+00:00 | 353 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\nM is number of strings and N is the length of String\nBuild time\n- Time complexity:\n $$O(m*n)$$\n\n\n- search time\n$$O(n*n)$$\n\n- Space complexity:\n$$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass MagicDictionary {\n\n private Node root;\n public MagicDictionary() {\n root = new Node();\n }\n \n public void buildDict(String[] dictionary) {\n for(String str: dictionary) {\n addString(root, 0, str);\n }\n }\n\n private void addString(Node node, int index, String str) {\n if(str.length() > index) {\n char ch = str.charAt(index);\n if(!node.hasChar(ch)) {\n node.addChar(ch);\n }\n addString(node.getChar(ch), ++index, str);\n } else {\n node.setWord();\n }\n }\n \n public boolean search(String searchWord) {\n return search(searchWord, 0, this.root, false);\n }\n\n private boolean search(String str, int index, Node node, boolean charChanged) {\n if(index < str.length()) {\n char ch = str.charAt(index);\n if(charChanged) {\n return node.hasChar(ch) && search(str, index+1, node.getChar(ch), true);\n } else {\n boolean found = false;\n for(char key : node.getAllChars().keySet()) {\n if(!found && key != ch) {\n found = search(str, index+1, node.getChar(key), true);\n }\n }\n return found || node.hasChar(ch) && search(str, index+1, node.getChar(ch), false);\n }\n \n } \n return index == str.length() && charChanged && node.isWord();\n }\n\n\n private class Node {\n private Map<Character, Node> chars;\n private boolean isWord;\n\n public Node() {\n this.chars = new HashMap<>();\n }\n public boolean isWord() {\n return this.isWord;\n }\n\n public void setWord(){\n this.isWord = true;\n }\n\n public boolean hasChar(char ch) {\n return chars.containsKey(ch);\n }\n\n public Node getChar(char ch) {\n return this.chars.get(ch);\n }\n\n public void addChar(char ch) {\n this.chars.put(ch, new Node());\n }\n\n public Map<Character, Node> getAllChars() {\n return this.chars;\n }\n\n @Override\n public String toString() {\n return "Mapping: " + this.chars + " isWord: " + this.isWord;\n }\n\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n``` | 1 | 0 | ['Java'] | 0 |
implement-magic-dictionary | C# Solution using Trie | c-solution-using-trie-by-mohamedabdelety-hof2 | \npublic class Node{\n public bool endWord;\n public Dictionary<char,Node> childs;\n public Node(bool _endWord = false){\n childs = new Dictiona | mohamedAbdelety | NORMAL | 2023-11-05T08:07:16.585774+00:00 | 2023-11-05T08:07:16.585796+00:00 | 30 | false | ```\npublic class Node{\n public bool endWord;\n public Dictionary<char,Node> childs;\n public Node(bool _endWord = false){\n childs = new Dictionary<char,Node>();\n endWord = _endWord;\n }\n}\n\npublic class MagicDictionary {\n Node head;\n\n public MagicDictionary() {\n head = new Node();\n }\n \n public void BuildDict(string[] dictionary) {\n foreach(var word in dictionary){\n var cur = head;\n foreach(var c in word){\n if(!cur.childs.ContainsKey(c))\n cur.childs.Add(c,new Node());\n cur = cur.childs[c];\n }\n cur.endWord = true;\n }\n }\n \n public bool Search(string searchWord) {\n int n = searchWord.Length;\n bool dfs(int idx, Node node,int dismatch){\n if(dismatch > 1) return false;\n if(idx >= n && node.endWord && dismatch == 1)return true;\n if(idx >= n) return false;\n char c = searchWord[idx];\n bool res = false;\n foreach(var kv in node.childs){\n if(kv.Key == c)\n res |= dfs(idx + 1,kv.Value,dismatch);\n else \n res |= dfs(idx + 1,kv.Value,dismatch + 1);\n }\n return res;\n }\n return dfs(0,head,0);\n }\n}\n\n``` | 1 | 0 | ['Depth-First Search', 'Trie', 'C#'] | 0 |
implement-magic-dictionary | c++ using hashmap; | c-using-hashmap-by-sanket33245-ywdk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sanket33245 | NORMAL | 2023-08-25T21:42:33.108697+00:00 | 2023-08-25T21:42:33.108725+00:00 | 117 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass MagicDictionary {\npublic:\n unordered_map<string,int>mp;\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> d) {\n for(auto it:d){\n mp[it]++;\n }\n }\n \n bool search(string s) {\n \n for(auto it:mp){\n int count=0;\n string temp=it.first;\n if(temp.size()==s.size()){\n for(int i=0;i<s.size();i++){\n if(s[i]!=temp[i]){\n count++;\n }\n }\n if(count==1){\n return 1;\n \n }\n }\n \n }\n return 0;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['Hash Table', 'C++'] | 0 |
implement-magic-dictionary | [C++] Intuitive & Simple Beginner Friendly TRIE Solution | c-intuitive-simple-beginner-friendly-tri-3myx | Intuitive Trie Solution, the insert operation is same as the basic trie insert operation. For searching just replace each character of searchWord one-by-one and | shrut_23 | NORMAL | 2023-08-23T10:22:22.030077+00:00 | 2023-08-23T16:13:53.505949+00:00 | 19 | false | Intuitive Trie Solution, the insert operation is same as the basic trie insert operation. For searching just replace each character of `searchWord` one-by-one and check whether we are not relacing the original character (since we need to change 1 character).\n\n# Time Complexity\n- Building the Trie: `O(n * m)`, where n is the number of words in the dictionary and m is the average length of words.\n- Searching for Possible Matches: `O(m * 26) ~ O(m)`, where m is the length of the search word.\n\n# Space Complexity\n- Trie Data Structure: `O(n * m)`, where n is the number of words in the dictionary and m is the average length of words.\n- Recursive Calls (Call Stack): `O(m)`, where m is the length of the search word.\n\n\n```\nstruct Node{\n Node* links[26];\n bool flag=false;\n\n bool containsKey(char ch){\n return links[ch-\'a\']!=NULL;\n }\n void put(char ch, Node* node){\n links[ch-\'a\']=node;\n }\n Node* get(char ch){\n return links[ch-\'a\'];\n }\n void setEnd(){\n flag=true;\n }\n bool isEnd(){\n return flag;\n }\n};\n\nclass MagicDictionary {\nprivate: \n Node* root;\n\n void insert(string word){\n Node* node=root;\n for(int i=0;i<word.length();i++){\n if(!node->containsKey(word[i])){\n node->put(word[i], new Node());\n }\n node=node->get(word[i]);\n }\n node->setEnd();\n }\n\n bool searchUtil(string word){\n Node* node=root;\n for(int i=0;i<word.length();i++){\n if(!node->containsKey(word[i])){\n return false;\n }\n node=node->get(word[i]);\n }\n return node->isEnd();\n }\n\npublic:\n MagicDictionary() {\n root=new Node();\n }\n \n void buildDict(vector<string> dictionary) {\n for(string s:dictionary){\n insert(s);\n }\n }\n \n bool search(string word) {\n int n=word.length();\n for(int i=0;i<n;i++){\n char original=word[i];\n for(int j=0;j<26;j++){\n char replacement = \'a\' + j;\n if(replacement != original){\n word[i] = replacement;\n if(searchUtil(word)){\n return true;\n }\n }\n }\n word[i]=original;\n }\n\n return false;\n }\n};\n``` | 1 | 0 | ['String', 'Design', 'Trie', 'C++'] | 0 |
implement-magic-dictionary | TRIE + DEPTH FIRST SEARCH || BEATS 50% || JAVA || EASY CODE | trie-depth-first-search-beats-50-java-ea-mb1t | Code\n\nclass TrieNode {\n Map<Character, TrieNode> children;\n boolean isEnd;\n TrieNode() {\n children = new HashMap<>();\n isEnd = fal | youssef1998 | NORMAL | 2023-06-25T09:23:14.108917+00:00 | 2023-06-25T09:23:14.108945+00:00 | 191 | false | # Code\n```\nclass TrieNode {\n Map<Character, TrieNode> children;\n boolean isEnd;\n TrieNode() {\n children = new HashMap<>();\n isEnd = false;\n }\n}\n\nclass Trie {\n private final TrieNode root = new TrieNode();\n Trie(){}\n \n public void insert(String str) {\n TrieNode current = root;\n for (Character c: str.toCharArray()) {\n TrieNode child = current.children.get(c);\n if(child == null) {\n child = new TrieNode();\n current.children.put(c, child);\n }\n current = child;\n }\n current.isEnd = true;\n }\n \n public boolean search(String str) {\n return dfs(root, 0, str, 0);\n }\n \n private boolean dfs(TrieNode node, int index, String str, int changed) {\n if(index == str.length() && node.isEnd && changed == 1) return true;\n if(changed == 2 || index >= str.length()) return false;\n for (Map.Entry<Character, TrieNode> child: node.children.entrySet()) {\n if(dfs(child.getValue(), index+1, str, child.getKey() == str.charAt(index) ? changed : changed + 1))\n return true;\n }\n return false;\n }\n}\n\n\nclass MagicDictionary {\n private final Trie trie = new Trie();\n public MagicDictionary() {\n\n }\n\n public void buildDict(String[] dictionary) {\n for (String word: dictionary)\n trie.insert(word);\n }\n\n public boolean search(String searchWord) {\n return trie.search(searchWord);\n }\n}\n``` | 1 | 0 | ['String', 'Depth-First Search', 'Design', 'Trie', 'Java'] | 0 |
implement-magic-dictionary | ✨ JavaScript - Clean Solution Using Trie | javascript-clean-solution-using-trie-by-rnnwr | \nvar MagicDictionary = function() {\n this.trie = {\n children: {}, \n }\n};\n\n/** \n * @param {string[]} dictionary\n * @return {void}\n */\nMagicDictio | ngseke | NORMAL | 2023-06-23T17:21:34.019853+00:00 | 2023-06-23T17:30:21.610616+00:00 | 51 | false | ```\nvar MagicDictionary = function() {\n this.trie = {\n children: {}, \n }\n};\n\n/** \n * @param {string[]} dictionary\n * @return {void}\n */\nMagicDictionary.prototype.buildDict = function(dictionary) {\n dictionary.forEach(word => {\n let current = this.trie\n\n ;[...word].forEach((char, index, { length }) => {\n const node = current.children[char] ?? { children: {} }\n current.children[char] = node\n\n const isEnd = index === length - 1\n if (isEnd) node.isEnd = true\n \n current = node\n })\n })\n};\n\n/** \n * @param {string} searchWord\n * @return {boolean}\n */\nMagicDictionary.prototype.search = function(searchWord) {\n const dfs = (index, trie, isChanged) => {\n if (index === searchWord.length) {\n return trie?.isEnd && isChanged\n }\n \n return Object.keys(trie.children)\n .some((key) => {\n const isSame = key === searchWord[index]\n if (isChanged && !isSame) return false\n\n return dfs(\n index + 1, \n trie.children[key], \n isChanged || !isSame\n )\n })\n }\n\n return dfs(0, this.trie, false)\n}; \n``` | 1 | 0 | ['Tree', 'Depth-First Search', 'Trie', 'Recursion', 'JavaScript'] | 0 |
implement-magic-dictionary | [Java] Simple Trie solution | java-simple-trie-solution-by-ytchouar-j1ad | java\nclass MagicDictionary {\n private final TrieNode root;\n\n public MagicDictionary() {\n this.root = new TrieNode();\n }\n \n public | YTchouar | NORMAL | 2023-05-26T05:54:10.669398+00:00 | 2023-05-28T06:37:21.885952+00:00 | 1,398 | false | ```java\nclass MagicDictionary {\n private final TrieNode root;\n\n public MagicDictionary() {\n this.root = new TrieNode();\n }\n \n public void buildDict(final String[] dictionary) {\n for(String word : dictionary)\n this.buildDictHelper(this.root, word);\n }\n\n public void buildDictHelper(TrieNode root, final String word) {\n for(int i = 0; i < word.length(); i++) {\n final int index = word.charAt(i) - \'a\';\n\n if(root.nextCharacters()[index] == null)\n root.nextCharacters()[index] = new TrieNode();\n\n root = root.nextCharacters()[index];\n }\n root.isWord(true);\n }\n \n public boolean search(final String searchWord) {\n return this.dfs(this.root, searchWord, 0, false);\n }\n\n public boolean dfs(final TrieNode root, final String searchWord, final int index, final boolean mismatch) {\n if (index == searchWord.length()) \n return (root.isWord() && index == searchWord.length() && mismatch);\n \n final int j = searchWord.charAt(index) - \'a\';\n\n if (!mismatch) {\n for (int i = 0; i < 26; i++) {\n if (i == j || root.nextCharacters()[i] == null)\n continue;\n if (dfs(root.nextCharacters()[i], searchWord, index + 1, true))\n return true;\n }\n }\n if (root.nextCharacters()[j] != null && dfs(root.nextCharacters()[j], searchWord, index + 1, mismatch))\n return true;\n return false;\n }\n\n private final class TrieNode {\n private final TrieNode[] nextCharacters;\n private boolean isWord;\n\n public TrieNode() {\n this.nextCharacters = new TrieNode[26];\n this.isWord = false;\n }\n\n public boolean isWord() {\n return this.isWord;\n }\n\n public void isWord(final boolean isWord) {\n this.isWord = isWord;\n }\n\n public TrieNode[] nextCharacters() {\n return this.nextCharacters;\n }\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n``` | 1 | 0 | ['Java'] | 0 |
implement-magic-dictionary | C++ | Map and Bitmask | c-map-and-bitmask-by-pikachuu-p3is | Code\n\nclass MagicDictionary {\n map<pair<string, string>, int> Map;\npublic:\n MagicDictionary() {\n \n }\n \n void buildDict(vector<str | pikachuu | NORMAL | 2022-12-28T13:50:13.607129+00:00 | 2022-12-28T13:50:13.607172+00:00 | 27 | false | # Code\n```\nclass MagicDictionary {\n map<pair<string, string>, int> Map;\npublic:\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dictionary) {\n for(string word: dictionary) {\n for(int i = 0; i < word.length(); i++) {\n Map[{word.substr(0, i), word.substr(i + 1)}] |= 1 << (word[i] - \'a\');\n }\n }\n }\n \n bool search(string searchWord) {\n for(int i = 0; i < searchWord.length(); i++) {\n if(Map.find({searchWord.substr(0, i), searchWord.substr(i + 1)}) != Map.end()) {\n if(Map[{searchWord.substr(0, i), searchWord.substr(i + 1)}] xor (1 << (searchWord[i] - \'a\'))) {\n return true;\n }\n }\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['Hash Table', 'String', 'Bit Manipulation', 'Design', 'C++'] | 0 |
implement-magic-dictionary | Trie simple approach | trie-simple-approach-by-sajnani-9djo | Intuition\nTrie approach\n\n# Approach\n1. Trie\n2. Recurse to find if there is a difference of one character in the most efficient way\n\n\n\n# Code\n\nclass M | sajnani | NORMAL | 2022-12-22T02:38:18.400174+00:00 | 2022-12-22T02:38:18.400214+00:00 | 693 | false | # Intuition\nTrie approach\n\n# Approach\n1. Trie\n2. Recurse to find if there is a difference of one character in the most efficient way\n\n\n\n# Code\n```\nclass MagicDictionary {\n\n Trie trie=new Trie();\n static class Trie{\n Map<Character,Trie> trieMap=new HashMap<Character,Trie>(); \n boolean eow=false;\n public String toString(){\n return trieMap.toString();\n }\n }\n\n public MagicDictionary() {\n \n }\n \n public void buildDict(String[] dictionary) {\n for(String word:dictionary){\n Trie tmpTrie=trie;\n\n for(char c:word.toCharArray()){\n tmpTrie.trieMap.putIfAbsent(c,new Trie());\n tmpTrie=tmpTrie.trieMap.get(c);\n } \n tmpTrie.eow=true; \n }\n\n \n }\n \n public boolean hasOneCharacDiff(String searchWord,int index,int runDiff,Trie trie){\n if(runDiff>1) return false;\n \n if(index>=searchWord.length()){\n if(runDiff==1 && trie.eow) return true;\n return false;\n }\n\n char c=searchWord.charAt(index);\n for(char k: trie.trieMap.keySet()){\n int addition=k==c?0:1;\n if(hasOneCharacDiff(searchWord,index+1,runDiff+addition,trie.trieMap.get(k)))return true;\n }\n \n return false;\n }\n\n public boolean search(String searchWord) {\n if(hasOneCharacDiff(searchWord,0,0,trie)) return true;\n return false;\n }\n\n \n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n``` | 1 | 0 | ['Java'] | 0 |
implement-magic-dictionary | C++ Easy hashing || In search_word function replace each char with all of 26 chars || Explained | c-easy-hashing-in-search_word-function-r-z369 | Complexity\n- Time complexity:\nO(n * m)-> for build_dictionary function,n is the number of words to be inserted into the data structure and m is the size of th | dee_stroyer | NORMAL | 2022-11-26T12:40:34.506669+00:00 | 2022-11-26T12:40:34.506702+00:00 | 31 | false | # Complexity\n- Time complexity:\nO(n * m)-> for **build_dictionary** function,n is the number of words to be inserted into the data structure and m is the size of that word. But as it is given that the maximum size of any word can be 100 so m can be neglected and it can be considered as O(n * 100) ~= O(N).\n \nO(n)-> for **searchWord** function, where n is the length of that word\n\n- Space complexity:\nO(n), unordered_set is used to store the words available in the dictionary\n\n# Code\n```\nclass MagicDictionary {\npublic:\n unordered_set<string>us;\n\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dictionary) {\n us.insert(dictionary.begin(), dictionary.end());\n }\n \n bool search(string searchWord) {\n for(int i = 0; i<searchWord.size(); i++){\n char org = searchWord[i];\n for(int k = 0; k<26; k++){\n int newchar = \'a\'+k;\n if(newchar == org)continue;\n searchWord[i]=newchar;\n if(us.count(searchWord)){\n return true;\n }\n }\n searchWord[i] = org;\n }\n\n return false;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'String', 'C++'] | 0 |
implement-magic-dictionary | [C++] Try all combinations || very easy to understand | c-try-all-combinations-very-easy-to-unde-wg2m | \nclass MagicDictionary {\npublic:\n unordered_set<string>st;\n MagicDictionary() {\n st.clear();\n }\n \n void buildDict(vector<string> a | NehaGupta_09 | NORMAL | 2022-10-02T16:56:23.907802+00:00 | 2022-10-02T16:56:23.907843+00:00 | 850 | false | ```\nclass MagicDictionary {\npublic:\n unordered_set<string>st;\n MagicDictionary() {\n st.clear();\n }\n \n void buildDict(vector<string> arr) {\n for(int i=0;i<arr.size();i++)\n {\n st.insert(arr[i]);\n }\n }\n \n bool search(string s) {\n for(int i=0;i<s.length();i++)\n {\n string temp=s;\n for(int k=0;k<26;k++)\n {\n char curr_char=char(k+\'a\');\n if(curr_char!=s[i])\n {\n temp[i]=char(k+\'a\');\n if(st.find(temp)!=st.end())\n {\n return true;\n }\n }\n }\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['C', 'C++'] | 0 |
implement-magic-dictionary | [C++] Try all combinations || very easy to understand | c-try-all-combinations-very-easy-to-unde-m9zy | \nclass MagicDictionary {\npublic:\n unordered_set<string>st;\n MagicDictionary() \n\t{\n st.clear(); \n }\n \n void buildDict(vector<str | akshat0610 | NORMAL | 2022-10-02T16:54:40.019958+00:00 | 2022-10-02T16:54:40.019999+00:00 | 402 | false | ```\nclass MagicDictionary {\npublic:\n unordered_set<string>st;\n MagicDictionary() \n\t{\n st.clear(); \n }\n \n void buildDict(vector<string> dict) \n\t{\n for(int i=0;i<dict.size();i++)\n {\n \t st.insert(dict[i]);\n\t }\n }\n \n bool search(string word) \n\t{\n for(int i=0;i<word.length();i++)\n {\n \t string temp_word = word;\n \t char temp_ch = word[i];\n \t \n \tfor(int j=0;j<26;j++)\n \t{\n \t char ch=char(j + \'a\');\n\t\t\t if(temp_ch != ch)\n\t\t\t {\n\t\t\t \ttemp_word[i] = ch;\n\t\t\t \t\n\t\t\t \tif(st.find(temp_word)!=st.end())\n\t\t\t \treturn true;\n\t\t\t }\t\n\t\t\t}\n\t\t}\n\t\treturn false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['C', 'C++'] | 0 |
implement-magic-dictionary | Java Solution | Using Trie | java-solution-using-trie-by-nitwmanish-0o77 | \nclass MagicDictionary {\n private static class Node {\n\t\tprivate char data;\n\t\tprivate boolean isEnd;\n\t\tprivate Node[] children;\n\n\t\tpublic Node( | nitwmanish | NORMAL | 2022-09-29T20:39:57.115374+00:00 | 2022-11-05T02:32:31.713329+00:00 | 89 | false | ```\nclass MagicDictionary {\n private static class Node {\n\t\tprivate char data;\n\t\tprivate boolean isEnd;\n\t\tprivate Node[] children;\n\n\t\tpublic Node(char data) {\n\t\t\tthis.data = data;\n\t\t\tthis.isEnd = false;\n\t\t\tthis.children = new Node[26];\n\t\t}\n\t}\n \n private Node root;\n \n public MagicDictionary() {\n root = new Node(\'/\');\n }\n \n private void insertWord(String word) {\n\t\tNode curr = root;\n\t\tfor (int i = 0; i < word.length(); i++) {\n\t\t\tint childIdx = word.charAt(i) - \'a\';\n\t\t\tif (curr.children[childIdx] == null) {\n\t\t\t\tcurr.children[childIdx] = new Node(word.charAt(i));\n\t\t\t}\n\t\t\tcurr = curr.children[childIdx];\n\t\t}\n\t\tcurr.isEnd = true;\n\t}\n \n public void buildDict(String[] dictionary) {\n for (String word : dictionary) {\n\t\t\tinsertWord(word);\n\t\t}\n }\n \n private boolean searchWord(String word) {\n\t\tNode curr = root;\n\t\tfor (int i = 0; i < word.length(); i++) {\n\t\t\tint childIdx = word.charAt(i) - \'a\';\n\t\t\tif (curr.children[childIdx] == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcurr = curr.children[childIdx];\n\t\t}\n\t\treturn curr.isEnd;\n\t}\n \n public boolean search(String searchWord) {\n\t\tHashSet<String> set = new HashSet<>();\n set.add(searchWord);\n boolean isFound = false;\n char[] charArr = searchWord.toCharArray();\n for (int i = 0; i < charArr.length; i++) {\n char oldChar = charArr[i];\n for (char ch = \'a\'; ch <= \'z\'; ch++) {\n charArr[i] = ch;\n String newString = new String(charArr);\n if (set.contains(newString)) {\n continue;\n }\n isFound = searchWord(newString);\n if (isFound) {\n break;\n }\n }\n charArr[i] = oldChar;\n if (isFound) {\n break;\n }\n }\n if (!isFound) {\n return false;\n }\n\t\treturn true;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n```\nSome Other Problems Using Trie Data Structure \n[1268 : Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/discuss/2638534/java-solution-using-trie-runtime-37-ms-beats-7219)\n[1233 : Remove Sub-Folders from the Filesystem](https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/2638522/java-solution-using-trie-runtime-43-ms-beats-9605)\n[648\t: Replace Words](https://leetcode.com/problems/replace-words/discuss/2638625/java-solution-using-trie-runtime-14-ms-beats-962219)\n[820\t: Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/discuss/2639021/java-solution-using-trie)\n[208\t: Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/discuss/2638657/simple-java-solution)\n[386\t: Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/discuss/2639107/java-solution-using-trie)\n[1023 : Camelcase Matching](https://leetcode.com/problems/camelcase-matching/discuss/2639736/java-solution-using-trie)\n[677\t: Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/discuss/2639994/java-solution-using-trie-and-hashmap)\n[676\t: Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/discuss/2640276/java-solution-using-trie)\n[421\t: Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/2643276/java-trie-approach-add-number-and-check-its-max-xor-on-fly-tc-on-and-sc-on)\n[792\t: Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/discuss/2643489/java-solutions-two-approach-1-using-trie-2-hashmap)\n[720\t: Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/discuss/2643586/java-solution-using-trie-dfs)\n[2261 : K Divisible Elements Subarrays](https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2643761/java-solution-sliding-window-trie-runtime-41-ms-faster-than-9846)\n[139\t: Word Break](https://leetcode.com/problems/word-break/discuss/2643915/java-solutions-two-approach-1-using-trie-bfs-2-dp)\n[211\t: Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/discuss/2643839/java-solution-using-trie-dfs)\n[1948 : Delete Duplicate Folders in System](https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/2646138/java-solution-using-trie-with-postorder-and-inorder-dfs-traversal)\n[1032 : Stream of Characters](https://leetcode.com/problems/stream-of-characters/discuss/2646970/java-solution-using-trie)\n[212. Word Search II](https://leetcode.com/problems/word-search-ii/discuss/2779677/Java-Solution-or-Using-Trie) | 1 | 0 | ['Tree', 'Trie', 'Java'] | 0 |
implement-magic-dictionary | C++ | Trie | Easy Solution | c-trie-easy-solution-by-sankalp_sharma_2-fmbr | \nclass MagicDictionary {\npublic:\n \n class Trie{\n public:\n Trie *child[26];\n bool isEnd;\n Trie()\n {\n | Sankalp_Sharma_29 | NORMAL | 2022-09-26T18:31:59.453195+00:00 | 2022-09-26T18:31:59.453243+00:00 | 14 | false | ```\nclass MagicDictionary {\npublic:\n \n class Trie{\n public:\n Trie *child[26];\n bool isEnd;\n Trie()\n {\n isEnd=false;\n for(int i=0;i<26;i++)\n child[i]=NULL;\n }\n };\n Trie *root=new Trie();\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dictionary) {\n \n for(string s:dictionary)\n {\n Trie *node=root; \n for(int i=0;i<s.size();i++)\n {\n if(!node->child[s[i]-\'a\'])\n {\n node->child[s[i]-\'a\']=new Trie();\n }\n node=node->child[s[i]-\'a\'];\n }\n node->isEnd=true;\n }\n }\n bool check(string s)\n {\n Trie *node=root;\n for(int i=0;i<s.size();i++)\n {\n if(node->child[s[i]-\'a\']==NULL)\n return false;\n node=node->child[s[i]-\'a\'];\n }\n return node->isEnd;\n }\n bool search(string searchWord) {\n \n \n string s=searchWord;\n int n=searchWord.size();\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<26;j++)\n {\n if(\'a\'+j==searchWord[i])\n continue;\n s[i]=\'a\'+j;\n if(check(s))\n {\n return true;\n }\n }\n s[i]=searchWord[i];\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['Trie', 'C'] | 0 |
implement-magic-dictionary | [C++] Trie + DFS | Try all combinations | c-trie-dfs-try-all-combinations-by-nilab-w8ls | ```\nclass MagicDictionary {\nprivate:\n struct Node{\n Node arr[26];\n bool end = false;\n };\n Node root;\npublic:\n MagicDictionary | nilabjodey | NORMAL | 2022-09-26T17:31:33.723371+00:00 | 2022-09-26T17:31:33.723414+00:00 | 458 | false | ```\nclass MagicDictionary {\nprivate:\n struct Node{\n Node* arr[26];\n bool end = false;\n };\n Node* root;\npublic:\n MagicDictionary() {\n root = new Node();\n }\n \n void trie_insert(string &word){\n Node* node = root;\n for(int i = 0; i < word.size(); i++){\n if(node->arr[word[i] - \'a\'] == NULL){\n node->arr[word[i] - \'a\'] = new Node();\n }\n node = node->arr[word[i] - \'a\'];\n }\n node->end = true;\n }\n \n void buildDict(vector<string> dictionary) {\n for(auto w: dictionary){ \n trie_insert(w);\n }\n }\n \n bool trie_search(string &word, Node* cur){\n for(int i = 0; i < word.size(); i++){\n if(cur->arr[word[i] - \'a\'] == NULL) return false;\n cur = cur->arr[word[i] - \'a\'];\n }\n return cur->end;\n }\n \n bool search(string searchWord) {\n for(int i = 0; i < searchWord.size(); i++){\n string temp = searchWord;\n for(int j = 0; j < 26; j++){\n char c = temp[i];\n temp[i] = \'a\' + j;\n if(temp == searchWord){\n temp[i] = c;\n continue;\n }\n if(trie_search(temp, root)) return true;\n temp[i] = c;\n }\n }\n return false;\n }\n}; | 1 | 0 | ['Depth-First Search', 'Trie'] | 0 |
implement-magic-dictionary | Cpp Solution using trie | cpp-solution-using-trie-by-sanket_jadhav-yma7 | ```\nclass node{\n public:\n node v[26];\n int end=0;\n \n bool ispresent(char c){\n return this->v[c-\'a\']!=NULL;\n }\n \n void c | Sanket_Jadhav | NORMAL | 2022-09-23T06:04:30.236012+00:00 | 2022-09-23T06:04:30.236048+00:00 | 388 | false | ```\nclass node{\n public:\n node* v[26];\n int end=0;\n \n bool ispresent(char c){\n return this->v[c-\'a\']!=NULL;\n }\n \n void create(char c,node* n){\n this->v[c-\'a\']=n;\n }\n \n void setend(){\n this->end=1;\n }\n};\n\nclass trie{\n public:\n node* root=new node();\n \n void insert(string key){\n node* r1=root;\n for(auto ele:key){\n \n if(!r1->ispresent(ele)){\n r1->create(ele,new node()); \n }\n \n r1=r1->v[ele-\'a\'];\n }\n \n r1->setend();\n }\n \n bool func(string s,int j,node* rm){\n \n for(j;j<s.size();j++){\n if(!rm->ispresent(s[j]))return false;\n \n rm=rm->v[s[j]-\'a\'];\n }\n \n return rm->end;\n }\n \n \n bool search(string s){\n node* r1=root;\n int a=0;\n \n for(int j=0;j<s.size();j++){\n \n for(int i=0;i<26;i++){\n if(r1->ispresent(char(\'a\'+i)) && s[j]-\'a\'!=i){\n if(func(s,j+1,r1->v[i]))return true; \n }\n } \n \n if(r1->ispresent(s[j]))r1=r1->v[s[j]-\'a\'];\n else return false;\n }\n \n return false;\n }\n \n};\n\nclass MagicDictionary {\npublic:\n trie* root;\n MagicDictionary() {\n root=new trie();\n }\n \n void buildDict(vector<string> dictionary) {\n for(auto ele:dictionary){\n root->insert(ele);\n }\n }\n \n bool search(string searchWord) {\n return root->search(searchWord);\n }\n}; | 1 | 0 | ['Trie', 'C++'] | 0 |
implement-magic-dictionary | c++ | using trie | low T.C. | c-using-trie-low-tc-by-venomhighs7-6rm7 | ```\nclass node{\npublic:\n node links[26];\n bool flag=false;\n};\n\nclass MagicDictionary {\n node root;\npublic:\n MagicDictionary() {\n r | venomhighs7 | NORMAL | 2022-09-18T10:36:34.207470+00:00 | 2022-09-18T10:36:34.207507+00:00 | 187 | false | ```\nclass node{\npublic:\n node* links[26];\n bool flag=false;\n};\n\nclass MagicDictionary {\n node* root;\npublic:\n MagicDictionary() {\n root=new node();\n }\n \n void addKey(string s) {\n node* temp=root;\n \n for(int i=0; i<s.length(); i++) {\n if(temp->links[s[i]-\'a\']==NULL) temp->links[s[i]-\'a\']=new node();\n temp=temp->links[s[i]-\'a\'];\n }\n \n temp->flag=true;\n }\n \n void buildDict(vector<string> dictionary) {\n for(auto word:dictionary) {\n addKey(word);\n }\n }\n \n bool util(string s, node* temp, int i=0, bool changed=false) {\n if(i==s.length() && temp->flag && changed) return true;\n if(i==s.length()) return false;\n \n if(changed) {\n if(!temp->links[s[i]-\'a\']) return false;\n else return util(s, temp->links[s[i]-\'a\'], i+1, changed);\n } else {\n for(int j=0; j<26; j++) {\n if(s[i]!=\'a\'+j && temp->links[j] && util(s, temp->links[j], i+1, !changed)) return true;\n }\n \n if(temp->links[s[i]-\'a\'] && util(s, temp->links[s[i]-\'a\'], i+1, changed)) return true;\n }\n \n return false;\n }\n \n bool search(string searchWord) {\n return util(searchWord, root);\n }\n}; | 1 | 0 | [] | 0 |
implement-magic-dictionary | Python | DFS on a Trie | Notes | python-dfs-on-a-trie-notes-by-rktayal-i8hs | \n/*\nwe can approach this problem using trie. Problem is very similar to \nAdd and search word data structures.\nWe can create a standard trie and search for w | rktayal | NORMAL | 2022-08-18T01:12:21.834663+00:00 | 2022-08-18T01:12:21.834716+00:00 | 29 | false | ```\n/*\nwe can approach this problem using trie. Problem is very similar to \nAdd and search word data structures.\nWe can create a standard trie and search for words in that.\nif at all, we come across a character which is not present down the path,\nwe still continue to see if word is still searchable. If we are able to find the \nremaining word, we return True else we return False\n*/\n```\n```\nclass TrieNode():\n def __init__(self):\n self.end = False\n self.children = {}\n \nclass MagicDictionary:\n\n def __init__(self):\n self.root = TrieNode()\n\n def buildDict(self, dictionary: List[str]) -> None:\n def insert(index, root, word):\n if index == len(word):\n root.end = True\n return\n if word[index] not in root.children:\n root.children[word[index]] = TrieNode()\n insert(index+1, root.children[word[index]], word)\n for word in dictionary:\n insert(0, self.root, word)\n \n def search(self, searchWord: str) -> bool:\n def search_fun(index, root, changed):\n if index == len(searchWord):\n if root.end and changed:\n return True\n return False\n if not changed:\n for key, value in root.children.items():\n if key == searchWord[index]:\n continue\n if search_fun(index+1, value, True):\n return True\n \n if searchWord[index] not in root.children:\n return False\n else:\n return search_fun(index+1, root.children[searchWord[index]], changed)\n \n return search_fun(0, self.root, False)\n``` | 1 | 0 | ['Depth-First Search', 'Trie', 'Python'] | 0 |
implement-magic-dictionary | EASY TO UNDERSTAND || C++ || RECURSION || TRIE | easy-to-understand-c-recursion-trie-by-a-7zm8 | struct Trie{\n Trie child[26];\n bool isEnd;\n};\n\nclass MagicDictionary {\npublic:\n \n Trie root;\n \n MagicDictionary() {\n \n | aniketm | NORMAL | 2022-08-02T17:41:20.796800+00:00 | 2022-08-02T17:41:20.796847+00:00 | 136 | false | struct Trie{\n Trie *child[26];\n bool isEnd;\n};\n\nclass MagicDictionary {\npublic:\n \n Trie *root;\n \n MagicDictionary() {\n \n root = new Trie();\n for(int i=0;i<26;i++)\n root->child[i] = NULL;\n root->isEnd = false;\n }\n \n void insert(string &s,Trie *root){\n Trie *temp = root;\n for(int i=0;i<s.length();i++){\n int index = s[i]-\'a\';\n if(!temp->child[index])\n temp->child[index] = new Trie();\n temp = temp->child[index];\n }\n \n temp->isEnd = true;\n }//insert\n \n \n //k=0 => all characters are find till now\n //k=1 => one charaxters is missing\n \n bool find(string &s,int index,Trie *root ,int k){\n \n for(int i=index;i<s.length();i++){\n int index = s[i]-\'a\';\n if(k==1 && root->child[index]==NULL)\n return 0;\n \n if(k==0){ \n for(int j=0;j<26;j++){\n if(root->child[j] && j!=index){\n if(find(s,i+1,root->child[j],1))\n return 1;\n }\n }//j\n } \n \n if(root->child[index]==NULL)\n return 0;\n else\n root = root->child[index];\n //}//if\n \n }//i\n \n return (root!=NULL && root->isEnd && k==1);\n }\n \n void buildDict(vector<string> dict) {\n \n int i,j,n=dict.size();\n for(auto x:dict)\n insert(x,root);\n }\n \n bool search(string s) {\n \n Trie *temp = root;\n return find(s,0,temp,0);\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */ | 1 | 0 | ['Depth-First Search', 'Trie', 'C'] | 0 |
implement-magic-dictionary | 72% TC and 63% SC easy python solution | 72-tc-and-63-sc-easy-python-solution-by-gkyho | \ndef __init__(self):\n\tself.root = dict()\n\tself.root[\'end\'] = 0\n\ndef buildDict(self, dictionary: List[str]) -> None:\n\tfor word in dictionary:\n\t\tc = | nitanshritulon | NORMAL | 2022-07-16T09:45:57.430928+00:00 | 2022-07-16T09:45:57.430974+00:00 | 50 | false | ```\ndef __init__(self):\n\tself.root = dict()\n\tself.root[\'end\'] = 0\n\ndef buildDict(self, dictionary: List[str]) -> None:\n\tfor word in dictionary:\n\t\tc = self.root\n\t\tfor char in word:\n\t\t\tif(char not in c):\n\t\t\t\tc[char] = dict()\n\t\t\t\tc[char][\'end\'] = 0\n\t\t\tc = c[char]\n\t\tc[\'end\'] = 1\n\ndef search(self, searchWord: str) -> bool:\n\tc = self.root\n\ti = 0\n\treturn self.dfs(0, searchWord, c, False, 0)\n\ndef dfs(self, i, word, curr, flag, changed):\n\tif(i == len(word)):\n\t\treturn curr[\'end\'] and changed\n\ttemp = False\n\tfor child in curr:\n\t\tif(child == word[i]):\n\t\t\ttemp = temp or self.dfs(i+1, word, curr[child], curr[\'end\'], changed)\n\t\telif(child != \'end\' and changed == 0):\n\t\t\ttemp = temp or self.dfs(i+1, word, curr[child], curr[\'end\'], changed+1)\n\treturn temp\n``` | 1 | 1 | ['Trie', 'Python', 'Python3'] | 0 |
implement-magic-dictionary | [Java] Trie | java-trie-by-vcamarggo-s3mw | ```\nstatic class TrieTree {\n\n TrieNode root = new TrieNode(\' \');\n\n public void insert(String s) {\n TrieNode current = root;\n | vcamarggo | NORMAL | 2022-07-10T13:48:46.280418+00:00 | 2022-07-10T13:48:46.280462+00:00 | 67 | false | ```\nstatic class TrieTree {\n\n TrieNode root = new TrieNode(\' \');\n\n public void insert(String s) {\n TrieNode current = root;\n for (char c : s.toCharArray()) {\n current = current.children.computeIfAbsent(c, k -> new TrieNode(c));\n }\n current.isWord = true;\n current.fullWord = s;\n }\n\n //Allow max 1 wrong character and still return found.\n // E.g. Trie has hello and hollo, but would still return true for hallo because it has only 1 wrong char\n public boolean searchWithMax1WrongChar(String searchWord, int beginIndex, TrieTree.TrieNode root, boolean usedWildcard) {\n for (int i = beginIndex; i < searchWord.length(); i++) {\n char data = searchWord.charAt(i);\n //Use the boolean "usedWildcard" as a single-use possibility to ignore 1 char\n if (!usedWildcard) {\n for (TrieTree.TrieNode child : root.children.values()) {\n if (searchWithMax1WrongChar(searchWord, i + 1, child, true)) {\n return true;\n }\n }\n }\n if (!root.children.containsKey(data)) {\n return false;\n }\n root = root.children.get(data);\n }\n return root.isWord && !root.fullWord.equals(searchWord);\n }\n\n public boolean searchWithMax1WrongChar(String searchWord) {\n return searchWithMax1WrongChar(searchWord, 0, root, false);\n }\n\n static class TrieNode {\n char val;\n boolean isWord;\n String fullWord;\n Map<Character, TrieNode> children;\n\n public TrieNode(char val) {\n this.val = val;\n this.isWord = false;\n this.children = new HashMap<>();\n }\n }\n }\n\n TrieTree trie;\n\n public Trie1WrongChar() {\n\n }\n\n public void buildDict(String[] dictionary) {\n this.trie = new TrieTree();\n for (String word : dictionary) {\n trie.insert(word);\n }\n\n }\n\n public boolean search(String searchWord) {\n return trie.searchWithMax1WrongChar(searchWord);\n } | 1 | 0 | ['Trie'] | 0 |
implement-magic-dictionary | Python: Trie+DFS | python-triedfs-by-vokasik-7k0b | The idea:\n\n1. Create a trie from words. O(|words| \ max_word_len)\n2. Check each combination in the trie of the search_word with 1 char skipped. O(25\max_word | vokasik | NORMAL | 2022-06-25T02:40:01.834065+00:00 | 2022-06-25T02:41:57.337466+00:00 | 171 | false | The idea:\n\n1. Create a trie from words. O(|words| \\* max_word_len)\n2. Check each combination in the trie of the search_word with 1 char skipped. O(25\\*max_word_len^2) \nExclude from the search the exact search_word if it is present in the original dict\n\ne.g.\n```\nsearch_word=hello, dict: hello, hullo\n\n_ello -> False, because this is search_word=dict[0] and requirements is - need 1 char different\nh_llo -> True. We need to skip h[e]llo (0 diff) combination here and find h[u]llo (1 diff from the search_word)\nhe_lo -> False\nhel_o -> False\nhell_ -> False\n```\n\n```\nclass Node(object):\n def __init__(self):\n self.children = {}\n self.is_word = False\n\nclass MagicDictionary:\n def __init__(self):\n self.root = Node()\n\n def buildDict(self, dictionary: List[str]) -> None:\n # O(|words| * len(word))\n for w in dictionary:\n node = self.root\n for c in w:\n if c not in node.children:\n node.children[c] = Node()\n node = node.children[c]\n node.is_word = True\n\n def search(self, search_word: str) -> bool:\n def find(idx, node, skip_idx, changes):\n if idx == n:\n return node.is_word and changes == 1\n\n # skip one letter in search_word\n if skip_idx == idx:\n for c in node.children:\n # avoid finding the same search_word in the dict\n if c != search_word[skip_idx]:\n if (find(idx + 1, node.children[c], skip_idx, changes + 1)):\n return True\n # find the next letter in search_word\n elif search_word[idx] in node.children:\n return find(idx + 1, node.children[search_word[idx]], skip_idx, changes)\n \n # search_word next letter was not found in the trie\n return False\n\n # O(25*n^2), where n = len(search_word)\n n = len(search_word)\n for skip_idx in range(n):\n # O(25*n), where n = len(search_word)\n if find(0, self.root, skip_idx, 0):\n return True\n \n return False\n```\n | 1 | 0 | ['Depth-First Search', 'Trie', 'Python'] | 0 |
implement-magic-dictionary | #Accepted solution in C++ using Tries data structure (Very easy & intuitive) | accepted-solution-in-c-using-tries-data-a7w2x | \nclass Node {\n private:\n Node* links[26];\n bool flag = false;\n public:\n bool containsKey(char ch) {\n return links[ch-\'a\'] != null | yashrajyash | NORMAL | 2022-05-22T18:27:22.622464+00:00 | 2022-05-22T18:27:22.622506+00:00 | 62 | false | ```\nclass Node {\n private:\n Node* links[26];\n bool flag = false;\n public:\n bool containsKey(char ch) {\n return links[ch-\'a\'] != nullptr;\n }\n void put(char ch, Node* node) {\n links[ch-\'a\'] = node;\n }\n Node* get(char ch) {\n return links[ch-\'a\'];\n }\n bool isEnd() {\n return flag;\n }\n void setEnd() {\n flag = true;\n }\n};\n\nclass MagicDictionary {\nprivate:\n Node* root;\npublic:\n MagicDictionary() {\n root = new Node();\n }\n \n void buildDict(vector<string> dictionary) {\n for(auto word : dictionary) {\n Node* node = root;\n for(int i=0; i<word.length(); i++) {\n if(!node->containsKey(word[i])) {\n node->put(word[i], new Node());\n }\n node = node->get(word[i]);\n }\n node->setEnd();\n }\n }\n bool dfs(string word) {\n Node* node = root;\n for(int i=0; i<word.length(); i++) {\n if(!node->containsKey(word[i])) return false;\n node = node->get(word[i]);\n }\n return node->isEnd();\n }\n bool search(string searchWord) {\n for(int i=0; i<searchWord.length(); i++) {\n char back = searchWord[i];\n for(char j=\'a\'; j<=\'z\'; j++) {\n if(j == back) continue;\n searchWord[i] = j;\n if(dfs(searchWord)) return true;\n }\n searchWord[i] = back;\n }\n return false;\n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */\n``` | 1 | 0 | ['Depth-First Search', 'C'] | 0 |
implement-magic-dictionary | trie | trie-by-biswajit2329-i1f1 | class MagicDictionary {\npublic:\n struct node\n {\n char val;\n nodearr[26]={NULL};\n bool isend;\n node(char ch)\n {\ | biswajit2329 | NORMAL | 2022-05-18T03:05:19.994024+00:00 | 2022-05-18T03:05:19.994061+00:00 | 91 | false | class MagicDictionary {\npublic:\n struct node\n {\n char val;\n node*arr[26]={NULL};\n bool isend;\n node(char ch)\n {\n val=ch;\n isend=false;\n }\n };\n node*root=new node(\'\\0\');\n void insert(string word)\n {\n node*temp=root;\n for(int i=0;i<word.size();i++)\n {\n if(temp->arr[word[i]-\'a\']==NULL)\n {\n temp->arr[word[i]-\'a\']=new node(word[i]);\n }\n temp=temp->arr[word[i]-\'a\'];\n }\n temp->isend=true;\n }\n \n \n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> words) {\n \n for(int i=0;i<words.size();i++)\n {\n insert(words[i]);\n }\n \n }\n \n bool Search(node*temp,string word,int ind,int count)\n {\n if(ind==word.size() && count==0 && temp->isend==true)\n {\n return true;\n }\n if(temp==NULL)\n {\n return false;\n }\n if(ind==word.size() && count!=0)\n {\n return false;\n }\n if(ind>=word.size())\n {\n return false;\n }\n if(count==0 && temp->arr[word[ind]-\'a\']==NULL) \n {\n return false;\n }\n bool res=false;\n for(int i=0;i<26;i++)\n {\n if(temp->arr[i]!=NULL && (word[ind]-\'a\')!=i && count==1)\n {\n bool ans=Search(temp->arr[i],word,ind+1,count-1);\n res|=ans;\n }\n }\n return res | Search(temp->arr[word[ind]-\'a\'],word,ind+1,count);\n }\n \n bool search(string word) {\n \n return Search(root,word,0,1);\n \n }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary* obj = new MagicDictionary();\n * obj->buildDict(dictionary);\n * bool param_2 = obj->search(searchWord);\n */ | 1 | 0 | ['Trie', 'C', 'C++'] | 0 |
implement-magic-dictionary | [C++] Trie solution with complexity analysis | c-trie-solution-with-complexity-analysis-oqa3 | \nclass MagicDictionary {\nprivate:\n struct Trie {\n private:\n bool isEnd = false;\n Trie *children[26];\n public:\n Trie () {\n | tinfu330 | NORMAL | 2022-05-10T17:58:23.072187+00:00 | 2022-05-10T17:58:23.072212+00:00 | 142 | false | ```\nclass MagicDictionary {\nprivate:\n struct Trie {\n private:\n bool isEnd = false;\n Trie *children[26];\n public:\n Trie () {\n for (int i = 0; i < 26; i++) {\n children[i] = NULL;\n }\n }\n \n void insert(string &s) {\n Trie *curr = this;\n for (char &c : s) {\n int cVal = c - \'a\';\n if (curr->children[cVal] == NULL) {\n curr->children[cVal] = new Trie();\n }\n curr = curr->children[cVal];\n }\n curr->isEnd = true;\n }\n \n bool magicSearch(Trie *curr, string &s, int i, int diff) {\n if (diff < 0) return false;\n if (i == s.size()) return (curr->isEnd && diff == 0);\n for (int j = 0; j < 26; j++) {\n if (curr->children[j] == NULL) continue;\n if (magicSearch(curr->children[j], s, i + 1, diff - (s[i] != \'a\' + j))) {\n return true;\n }\n }\n return false;\n }\n };\n Trie trie;\n \npublic:\n MagicDictionary() {\n \n }\n \n\t// Time complexity: O(MN), M = dictionary size, N = string size\n\t// Space complexity: O(MN), becuase the worse case is that we have to store every character in trie\n void buildDict(vector<string> dictionary) {\n for (string &s : dictionary) {\n trie.insert(s);\n }\n }\n \n\t// Time complexity: O(MN), because the worse case is that we have to search each character in trie\n\t// Space complexity: O(N), due to recursion, in the worse case we will have a stack size poportional to the longest word\n bool search(string searchWord) {\n return trie.magicSearch(&trie, searchWord, 0, 1);\n }\n};\n``` | 1 | 0 | ['Backtracking', 'Trie', 'C', 'C++'] | 0 |
implement-magic-dictionary | python solution || hash with dict || faster than 60% || time: O(nk) || space: O(nk) | python-solution-hash-with-dict-faster-th-3y9b | \tclass MagicDictionary:\n\n\t\tdef init(self):\n\t\t\tself.magic_dict = dict() \n\n\t\tdef buildDict(self, dictionary: List[str]) -> None:\n\t\t\tfor word in d | longyunhust | NORMAL | 2022-05-02T16:23:24.977617+00:00 | 2022-05-03T03:40:23.559383+00:00 | 45 | false | \tclass MagicDictionary:\n\n\t\tdef __init__(self):\n\t\t\tself.magic_dict = dict() \n\n\t\tdef buildDict(self, dictionary: List[str]) -> None:\n\t\t\tfor word in dictionary: \n\t\t\t\tword_len = len(word)\n\t\t\t\tfor i in range(word_len): \n\t\t\t\t\tkey = word[:i] + \'*\' + word[i+1:]\n\t\t\t\t\tif key not in self.magic_dict: \n\t\t\t\t\t\tself.magic_dict[key] = set()\n\t\t\t\t\t\tself.magic_dict[key].add(word[i])\n\t\t\t\t\telif key in self.magic_dict: \n\t\t\t\t\t\tself.magic_dict[key].add(word[i])\n\n\t\tdef search(self, searchWord: str) -> bool:\n\t\t\tsearch_word_len = len(searchWord)\n\t\t\tfor i in range(search_word_len): \n\t\t\t\tsearch_string = searchWord[:i] + \'*\' + searchWord[i+1:]\n\t\t\t\tif search_string in self.magic_dict:\n\t\t\t\t\tif len(self.magic_dict[search_string]) == 1 and searchWord[i] not in self.magic_dict[search_string]:\n\t\t\t\t\t\treturn True\n\t\t\t\t\telif len(self.magic_dict[search_string]) >= 2: \n\t\t\t\t\t\treturn True\n\t\t\treturn False \n\n\t# Your MagicDictionary object will be instantiated and called as such:\n\t# obj = MagicDictionary()\n\t# obj.buildDict(dictionary)\n\t# param_2 = obj.search(searchWord) | 1 | 0 | [] | 0 |
implement-magic-dictionary | [Java]Trie || Recursion | javatrie-recursion-by-javacoder911-v2hr | ```\nclass MagicDictionary {\n TrieNode root;\n public MagicDictionary() {\n root = new TrieNode();\n }\n \n public void buildDict(String[ | javaCoder911 | NORMAL | 2022-03-20T05:50:21.941165+00:00 | 2022-03-20T05:50:21.941208+00:00 | 132 | false | ```\nclass MagicDictionary {\n TrieNode root;\n public MagicDictionary() {\n root = new TrieNode();\n }\n \n public void buildDict(String[] dictionary) {\n for(String s: dictionary){\n insertWord(s);\n }\n }\n \n public boolean search(String searchWord) {\n return search(searchWord, true, root, 0);\n }\n \n private boolean search(String word, boolean canVary, TrieNode root, int index){\n TrieNode cur = root;\n if(index == word.length())\n return !canVary && root.eow;\n for(int i=index;i<word.length();i++){\n if(canVary){\n for(int j=0;j<26;j++){\n if(cur.children[j]!=null){\n if(search(word, ((word.charAt(i)-\'a\')==j), cur.children[j], i+1))\n return true;\n }\n }\n return false;\n } else {\n if(cur.children[word.charAt(i)-\'a\']==null)\n return false;\n cur = cur.children[word.charAt(i)-\'a\'];\n }\n }\n return !canVary && cur.eow;\n }\n \n private void insertWord(String word){\n TrieNode cur = root;\n for(int i=0;i<word.length();i++){\n int x = word.charAt(i)-\'a\';\n if(cur.children[x]==null)\n cur.children[x]=new TrieNode();\n cur = cur.children[x];\n }\n cur.eow = true;\n }\n}\n\nclass TrieNode {\n TrieNode[] children;\n boolean eow;\n public TrieNode(){\n eow = false;\n children = new TrieNode[26];\n }\n} | 1 | 0 | ['Trie', 'Java'] | 0 |
implement-magic-dictionary | Java solution | java-solution-by-user9210fp-6ezz | ```class MagicDictionary {\n List myList;\n\n public MagicDictionary() {\n myList = new LinkedList();\n }\n \n public void buildDict(Strin | user9210Fp | NORMAL | 2022-03-06T03:49:40.733785+00:00 | 2022-03-06T03:49:40.733812+00:00 | 111 | false | ```class MagicDictionary {\n List<String> myList;\n\n public MagicDictionary() {\n myList = new LinkedList<String>();\n }\n \n public void buildDict(String[] dictionary) {\n for(int i =0; i < dictionary.length; i++)\n {\n myList.add(dictionary[i]);\n }\n }\n \n public boolean search(String searchWord) {\n for(int i =0; i < myList.size(); i++)\n {\n if(myList.get(i).length() == searchWord.length())\n {\n int count = 0;\n String s = myList.get(i);\n int j = 0;\n for(int t =0; t < s.length(); t++)\n {\n if(s.charAt(t) != searchWord.charAt(j)){\n count++;\n }\n j++;\n }\n if(count == 1) return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */ | 1 | 0 | [] | 0 |
implement-magic-dictionary | [C++] Trie + Backtracking solution | c-trie-backtracking-solution-by-tinfu330-6tbn | \nclass Trie {\nprivate:\n vector<Trie *> child;\n bool isEnd;\npublic:\n Trie () : child(26, NULL) {\n isEnd = false;\n }\n \n void in | tinfu330 | NORMAL | 2022-01-11T07:27:12.271799+00:00 | 2022-01-11T07:29:32.927794+00:00 | 117 | false | ```\nclass Trie {\nprivate:\n vector<Trie *> child;\n bool isEnd;\npublic:\n Trie () : child(26, NULL) {\n isEnd = false;\n }\n \n void insert(string &s) {\n Trie *curr = this;\n for (char &c : s) {\n int cIndex = c - \'a\';\n if (curr->child[cIndex] == NULL) {\n curr->child[cIndex] = new Trie();\n }\n curr = curr->child[cIndex];\n }\n curr->isEnd = true;\n }\n \n bool helper(Trie *curr, string &s, int i, int cnt) {\n \n if (cnt > 1) return false;\n \n if (i == s.size()) {\n if (curr->isEnd && cnt == 1) return true;\n return false;\n }\n \n for (int k = 0; k < 26; k++) {\n if (curr->child[k] == NULL) continue;\n if (helper(curr->child[k], s, i + 1, (k == s[i] - \'a\' ? cnt : cnt + 1))) return true;\n }\n \n return false;\n }\n \n bool strangeSearch(string &s) {\n return helper(this, s, 0, 0);\n }\n};\n\nclass MagicDictionary {\nprivate:\n Trie trie;\npublic:\n MagicDictionary() {\n \n }\n \n void buildDict(vector<string> dictionary) {\n for (string &eachS : dictionary) {\n trie.insert(eachS);\n }\n }\n \n bool search(string searchWord) {\n return trie.strangeSearch(searchWord);\n }\n};\n``` | 1 | 0 | ['Backtracking', 'Trie', 'C', 'C++'] | 0 |
implement-magic-dictionary | ⌘[ Java ] 3 Solutions | Observations | Trie | HashMap | java-3-solutions-observations-trie-hashm-aiky | Solution 1 : \n TC : \n\t buildDict : O(n), where n is the number of words in the dictionary\n\t search : O(n*k), where k is the length of word we are checkin | Kaustubh_22 | NORMAL | 2022-01-05T04:00:01.222089+00:00 | 2022-01-18T17:57:22.983598+00:00 | 206 | false | # Solution 1 : \n* TC : \n\t* buildDict : `O(n) `, where `n` is the number of words in the dictionary\n\t* search : `O(n*k)`, where `k` is the length of word we are checking\n \n* SC : `O(n)`\n* Drawback : `Kills memory as the dictionary increases`\n```\nclass MagicDictionary {\n \n HashMap<Integer, HashSet<String>> map; \n\t// HashSet / Arraylist, doesn\'t make a diff bcz it is given in the question -> given a list of "different" words\n public MagicDictionary() {\n map = new HashMap<>();\n }\n \n public void buildDict(String[] dictionary) {\n for(String word : dictionary) {\n if(!map.containsKey(word.length())) {\n map.put(word.length(), new HashSet<String>());\n }\n map.get(word.length()).add(word);\n }\n }\n \n public boolean search(String searchWord) {\n if(!map.containsKey(searchWord.length()))\n return false;\n \n for(String words : map.get(searchWord.length())) {\n int count = 0;\n for(int i=0;i<searchWord.length();i++) {\n count += words.charAt(i) == searchWord.charAt(i) ? 0 : 1;\n }\n if(count == 1) return true;\n }\n return false;\n }\n}\n ```\n \n # Solution 2: \nThe given constraints is an intuition to use `Trie` data-structure.\nCode Observations : \n* `Search Operation` is not optimized as we are changing one char and searching for the complete word again.\n\nComplexity Analysis : \n* TC : `O(n*m) + O(k*26*k)`, where `k` is the length of word we are searching\n* SC : `O(n*m)`\n ```\n class Node {\n HashMap<Character, Node> children;\n boolean isEnd;\n Node() {\n this.children = new HashMap<>();\n this.isEnd = false;\n }\n}\nclass MagicDictionary {\n \n private Node root;\n private int maxLength;\n \n public MagicDictionary() {\n this.root = new Node();\n this.maxLength = 0;\n }\n \n public void buildDict(String[] dictionary) {\n for(String word : dictionary) {\n Node curr = this.root;\n maxLength = Math.max(maxLength, word.length());\n for(char ch : word.toCharArray()) {\n if(curr.children.get(ch) == null) \n curr.children.put(ch, new Node());\n curr = curr.children.get(ch);\n }\n curr.isEnd = true;\n }\n }\n \n public boolean search(String searchWord) {\n if(maxLength < searchWord.length()) \n return false;\n \n char[] W = searchWord.toCharArray();\n int n = W.length;\n Node curr = this.root;\n for(int i=0;i<n;i++) {\n char original = W[i];\n for(char ch=\'a\';ch<=\'z\';ch++) {\n if(ch != original) \n {\n W[i] = ch;\n // curr char changed -> search complete string\n if(searchWord(W)) return true;\n W[i] = original;\n }\n }\n }\n return false;\n }\n \n private boolean searchWord(char[] W) { \n Node curr = this.root;\n for(int i=0;i<W.length;i++) {\n if(curr.children.get(W[i]) == null) return false;\n curr = curr.children.get(W[i]);\n }\n return curr.isEnd;\n }\n}\n```\n\n# Solution 3 : \nThis approach is bit more optimized in `search(searchWord)` functionality.\n* Complexity of below solution would be better in average cases but in worst case, matches with the above solution.\n```\nclass Node {\n HashMap<Character, Node> children;\n boolean isEnd;\n Node() {\n this.children = new HashMap<>();\n this.isEnd = false;\n }\n}\nclass MagicDictionary {\n \n private Node root;\n private int maxLength;\n \n public MagicDictionary() {\n this.root = new Node();\n this.maxLength = 0;\n }\n \n public void buildDict(String[] dictionary) {\n for(String word : dictionary) {\n Node curr = this.root;\n maxLength = Math.max(maxLength, word.length());\n for(char ch : word.toCharArray()) {\n if(curr.children.get(ch) == null) \n curr.children.put(ch, new Node());\n curr = curr.children.get(ch);\n }\n curr.isEnd = true;\n }\n }\n \n public boolean search(String searchWord) {\n if(maxLength < searchWord.length()) \n return false;\n \n char[] W = searchWord.toCharArray();\n int n = W.length;\n Node curr = this.root;\n for(int i=0;i<n;i++) {\n char original = W[i];\n for(char ch=\'a\';ch<=\'z\';ch++) {\n if(curr.children.get(ch) == null) continue;\n if(ch != original) \n {\n W[i] = ch;\n // curr char changed -> search for string ahead\n if(searchWord(curr.children.get(W[i]), W, i+1)) return true;\n W[i] = original;\n }\n }\n\t\t\t// if we can not go ahead -> return false\n if(curr.children.get(W[i]) == null) return false;\n curr = curr.children.get(W[i]);\n }\n return false;\n }\n \n private boolean searchWord(Node curr, char[] W, int index) { \n // Node curr = this.root;\n for(int i=index;i<W.length;i++) {\n if(curr.children.get(W[i]) == null) return false;\n curr = curr.children.get(W[i]);\n }\n return curr.isEnd;\n }\n}\n``` | 1 | 0 | ['Trie', 'Java'] | 0 |
implement-magic-dictionary | Golang Hashmap | golang-hashmap-by-archaeoraptor-9cxt | golang\ntype MagicDictionary struct {\n\tneightbour map[string]int\n\torigin map[string]int\n}\n\nfunc Constructor() MagicDictionary {\n\tm := MagicDictiona | archaeoraptor | NORMAL | 2021-12-30T06:55:33.423569+00:00 | 2021-12-30T06:55:33.423670+00:00 | 86 | false | ```golang\ntype MagicDictionary struct {\n\tneightbour map[string]int\n\torigin map[string]int\n}\n\nfunc Constructor() MagicDictionary {\n\tm := MagicDictionary{map[string]int{}, map[string]int{}}\n\treturn m\n}\n\nfunc (this *MagicDictionary) BuildDict(dictionary []string) {\n\tfor _, word := range dictionary {\n\t\tthis.origin[word]++\n\t\tfor i, _ := range word {\n\t\t\tt := []byte(word)\n\t\t\tt[i] = \'_\'\n\t\t\tthis.neightbour[string(t)]++\n\t\t}\n\t}\n}\n\nfunc (this *MagicDictionary) Search(searchWord string) bool {\n\tcnt := this.origin[searchWord]\n\tfor i, _ := range searchWord {\n\t\tt := []byte(searchWord)\n\t\tt[i] = \'_\'\n\t\tif cnt > 1 || this.neightbour[string(t)] > cnt {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n``` | 1 | 0 | ['Go'] | 0 |
implement-magic-dictionary | JAVA SOLUTION | | 100% LESS MEMORY USE | | ~78.64% FASTER | java-solution-100-less-memory-use-7864-f-c7mc | \nclass MagicDictionary {\n HashSet<String> hs; \n public MagicDictionary() {\n hs = new HashSet<>();\n }\n \n public void buildDict(Stri | Rajnish_vedi | NORMAL | 2021-12-23T09:37:07.956512+00:00 | 2021-12-23T09:37:41.031712+00:00 | 137 | false | ```\nclass MagicDictionary {\n HashSet<String> hs; \n public MagicDictionary() {\n hs = new HashSet<>();\n }\n \n public void buildDict(String[] dictionary) {\n for(String s:dictionary){\n hs.add(s);\n }\n }\n \n public boolean search(String searchWord) {\n for(String s:hs){\n if(s.length()==searchWord.length()){\n int cnt = 0;\n for(int i = 0;i<searchWord.length();i++){\n if(s.charAt(i)!=searchWord.charAt(i))cnt++;\n }\n if(cnt==1) return true;\n }\n }\n return false;\n }\n}\n\n``` | 1 | 0 | ['Java'] | 0 |
implement-magic-dictionary | Easy Java Solution No extra space | easy-java-solution-no-extra-space-by-rag-8p7z | class MagicDictionary {\n \n\tString[] magicDictionary;\n public MagicDictionary() {}\n \n public void buildDict(String[] dictionary) {\n mag | raghu6306766 | NORMAL | 2021-10-30T15:27:20.259832+00:00 | 2021-10-30T15:27:20.259857+00:00 | 98 | false | class MagicDictionary {\n \n\tString[] magicDictionary;\n public MagicDictionary() {}\n \n public void buildDict(String[] dictionary) {\n magicDictionary = dictionary;\n }\n \n public boolean canMatch(String searchWord , String dictWord){\n if(dictWord.length() == searchWord.length() && !searchWord.equals(dictWord))\n for(int i = 0 ; i < dictWord.length() ; i++)\n if(searchWord.charAt(i) != dictWord.charAt(i)) \n return searchWord.substring(i+1).equals(dictWord.substring(i+1));\n \n return false;\n }\n \n public boolean search(String searchWord) {\n for(String dictWord : magicDictionary){\n if(canMatch(searchWord , dictWord)) return true;\n }\n return false;\n }\n} | 1 | 0 | ['Java'] | 0 |
maximize-win-from-two-segments | [Java/C++/Python] DP + Sliding Segment O(n) | javacpython-dp-sliding-segment-on-by-lee-bum4 | Intuition\nMaximize Win From One Segments,\ncan be solved by sliding window.\n\nNow we can slide the second segment,\nand get calculate the result from dp.\n\n\ | lee215 | NORMAL | 2023-02-04T16:15:42.255814+00:00 | 2023-02-05T07:56:09.276218+00:00 | 13,250 | false | # **Intuition**\nMaximize Win From **One** Segments,\ncan be solved by sliding window.\n\nNow we can slide the second segment,\nand get calculate the result from `dp`.\n<br>\n\n# **Explanation**\nMaintain a sliding segment(sliding window),\nwhere `A[i] - A[j] <= k`.\n\n`dp[k]` means the the maximum number\nwe can cover if you choose the **one** segments optimally\nin the first `k` elements.\n\nWhen we slide a segment from left to right,\nthe number of elements that we cover is `i - j + 1`\nand in the first `j` elements,\nwe can cover at most `dp[j]` elements,\nso we can cover `i - j + 1 + dp[j]` in total.\nUpdate the result `res` and finally return it.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public int maximizeWin(int[] A, int k) {\n int res = 0, n = A.length, j = 0, dp[] = new int[n + 1];\n for (int i = 0; i < n; ++i) {\n while (A[j] < A[i] - k)\n ++j;\n dp[i + 1] = Math.max(dp[i], i - j + 1);\n res = Math.max(res, i - j + 1 + dp[j]);\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n int maximizeWin(vector<int>& A, int k) {\n int res = 0, n = A.size(), j = 0;\n vector<int> dp(n + 1, 0);\n for (int i = 0; i < n; ++i) {\n while (A[j] < A[i] - k)\n ++j;\n dp[i + 1] = max(dp[i], i - j + 1);\n res = max(res, i - j + 1 + dp[j]);\n }\n return res;\n }\n```\n\n**Python**\n```py\n def maximizeWin(self, A, k):\n dp = [0] * (len(A) + 1)\n res = j = 0\n for i, a in enumerate(A):\n while A[j] < A[i] - k: j += 1\n dp[i + 1] = max(dp[i], i - j + 1)\n res = max(res, i - j + 1 + dp[j])\n return res\n```\n<br>\n\n# **Follow up**\nWhat if we want to solve `Maximize Win From K Segments`\nWe can solve it by this approach as well.\nSimply increase one linear `dp[i]` to `dp[k][i]`,\n`dp[k][i]` means the maixmum we can in the first `i` elements with `k` segments.\n<br>\n\n# More Similar Sliding Window Problems\nHere are some similar sliding window problems.\nAlso find more explanations and discussion.\nGood luck and have fun.\n\n- 2555. [Maximize Win From Two Segments](https://leetcode.com/problems/maximize-win-from-two-segments/discuss/3141449/JavaC%2B%2BPython-DP-%2B-Sliding-Segment-O(n))\n- 2537. [Count the Number of Good Subarrays](https://leetcode.com/problems/count-the-number-of-good-subarrays/discuss/3052559/C%2B%2BPython-Sliding-Window)\n- 2401. [Longest Nice Subarray](https://leetcode.com/problems/longest-nice-subarray/discuss/2527496/Python-Sliding-Window)\n- 2398. [Maximum Number of Robots Within Budget](https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2524838/Python-Sliding-Window-O(n))\n- 1838. [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/1175090/JavaC%2B%2BPython-Sliding-Window)\n- 1493. [Longest Subarray of 1\'s After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708112/JavaC%2B%2BPython-Sliding-Window-at-most-one-0)\n- 1425. [Constrained Subsequence Sum](https://leetcode.com/problems/constrained-subsequence-sum/discuss/597751/JavaC++Python-O(N)-Decreasing-Deque)\n- 1358. [Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/516977/JavaC++Python-Easy-and-Concise)\n- 1248. [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/419378/JavaC%2B%2BPython-Sliding-Window-atMost(K)-atMost(K-1))\n- 1234. [Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/408978/javacpython-sliding-window/)\n- 1004. [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/JavaC%2B%2BPython-Sliding-Window)\n- 930. [Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum/discuss/186683/)\n- 992. [Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/523136/JavaC%2B%2BPython-Sliding-Window)\n- 904. [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/discuss/170740/Sliding-Window-for-K-Elements)\n- 862. [Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/143726/C%2B%2BJavaPython-O(N)-Using-Deque)\n- 209. [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/discuss/433123/JavaC++Python-Sliding-Window)\n<br> | 184 | 0 | ['C', 'Python', 'Java'] | 23 |
maximize-win-from-two-segments | Sliding Window +DP O(n) | sliding-window-dp-on-by-priyanshu_chaudh-2pj8 | Intuition\n what if we were allowed to choose only one segment(sliding window)\n what if i save the last segment with maximum prizes that I can attain from 0<= | Priyanshu_Chaudhary_ | NORMAL | 2023-02-04T16:19:06.438147+00:00 | 2023-02-07T08:52:14.659295+00:00 | 5,504 | false | # Intuition\n* what if we were allowed to choose only one segment(sliding window)\n* what if i save the last segment with maximum prizes that I can attain from 0<=j<=i(dynamic programming)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* if I am currently at ith position, the maximum prizes I can attain \n**i-start+1** prizes such that **nums[i]-nums[start]<=k** using sliding window.\nNote\n(\n nums[i]-nums[start]<=k \n takes care of the condition (The length of each segment must be k)\n .Even if my length is smaller than k then there is going to be overlapping which is allowed.\n)\n\n* so suppose I can attain **i-start+1** prizes from the ith position , I will try to find the maximum prizes that can be attained in the subarray \nfrom **0<=i< start**(\n which can be calculated by dp\nthat is **dp[i]=max(i-start+1,dp[i-1])**;\n\n).\n# Complexity\n- Time complexity: amortised O(n)\n- Space complexity: O(n) (size of array dp)\n# Code\n```\nclass Solution\n{\npublic:\n int maximizeWin(vector<int> &nums, int k)\n {\n int n = nums.size(), start = 0, ans = 0;\n vector<int> dp(n);\n for (int i = 0; i < n; i++)\n {\n while (nums[i] - nums[start] > k)\n start++;\n \n ans = max(ans, i - start + 1 + (start > 0 ? dp[start - 1] : 0));\n dp[i] = max((i > 0 ? dp[i - 1] : 0), i - start + 1);\n }\n return ans;\n }\n};\n``` | 41 | 0 | ['Dynamic Programming', 'Sliding Window', 'C++'] | 5 |
maximize-win-from-two-segments | DP+Binary Search||C++||Recursive Solution | dpbinary-searchcrecursive-solution-by-ba-t62f | \nclass Solution {\npublic:\n vector<vector<int>>dp;\n int fn(int ind,vector<int>&arr,int segment,int k) \n {\n if(segment==0)\n retu | baibhavkr143 | NORMAL | 2023-02-04T16:19:04.619062+00:00 | 2023-02-13T06:48:06.899999+00:00 | 3,052 | false | ```\nclass Solution {\npublic:\n vector<vector<int>>dp;\n int fn(int ind,vector<int>&arr,int segment,int k) \n {\n if(segment==0)\n return 0;\n if(ind>=arr.size())\n return 0;\n if(dp[ind][segment]!=-1)\n return dp[ind][segment];\n \n int non_pick=fn(ind+1,arr,segment,k); \n int target=lower_bound(arr.begin(),arr.end(),arr[ind]+k+1)-arr.begin();\n int pick=target-ind; \n \n pick+=fn(target,arr,segment-1,k);\n \n return dp[ind][segment]= max(non_pick,pick);\n \n \n }\n \n int maximizeWin(vector<int>& arr, int k) {\n int n=arr.size();\n dp.resize(n,vector<int>(3,-1));\n \n return fn(0,arr,2,k);\n \n \n }\n};\n``` | 30 | 1 | ['Binary Search', 'Dynamic Programming', 'Recursion', 'C'] | 4 |
maximize-win-from-two-segments | ✅ Easy Sliding Window with DP + Visual Example ✅ | easy-sliding-window-with-dp-visual-examp-tx74 | Idea\n- Use sliding window along with 1D dynamic programming. \n- Sliding window will find all possible segments while dp array stores the maximum segment up to | L30XL1U | NORMAL | 2023-02-07T08:57:18.332855+00:00 | 2023-02-09T05:23:29.880759+00:00 | 1,040 | false | # Idea\n- Use sliding window along with 1D dynamic programming. \n- Sliding window will find all possible segments while `dp` array stores the maximum segment up to each index. \n- Combining these two concepts, sliding window is used for current segment length while `dp` finds a previous maximum segment. \n - Notice using this method means our segments will never overlap. \n\n##### Sliding Window\n- We increase our window while the segment is *less than or equal to* `k`.\n- Decrease our window when above condition is not satisifed. \n- We want to have a valid window with every iteration so we can check with `dp` for max segments. \n\n##### Dynamic Programming \n- Size $$n+1$$ to initialize `dp[0] = 0` for start max segment size. Conventional and convenient for most DP problems. \n- At each index, we store the maximum segment size up to that point.\n- The candidates for consideration: current segment length `start` to `end` and previous max segment `dp[start]`.\n\n\n# Example\n- Here is every iteration of case `[1, 1, 2, 2, 3, 3, 5]`\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int maximizeWin(vector<int>& prizePositions, int k) {\n int n = prizePositions.size();\n vector<int> dp(n+1, 0);\n int res = 0;\n for (int start = 0, end = 0; end < n; end++){\n while (prizePositions[end] - prizePositions[start] > k){\n start++;\n }\n dp[end+1] = max(dp[end], end-start+1);\n res = max(res, end-start+1 + dp[start]);\n }\n return res;\n }\n};\n```\n### Please upvote if this was helpful. Thanks! \n | 27 | 0 | ['C++'] | 1 |
maximize-win-from-two-segments | Prefix Count || O(n) || sliding window || with Image | prefix-count-on-sliding-window-with-imag-9d58 | Intuition\nSince we only need to choose two segement , why not consider one to left and one to right for all index \'i\'\n\n\n\n# Approach\nUsing sliding window | pkpawan | NORMAL | 2023-02-04T17:09:04.518119+00:00 | 2023-02-04T17:12:00.517717+00:00 | 3,008 | false | # Intuition\nSince we only need to choose two segement , why not consider one to left and one to right for all index \'i\'\n\n\n\n# Approach\nUsing sliding window we can find the max count for [0,i] for all i we storre in prefix array,\nsimilarly if we can find for suffix array .\nThe max value of [0,i] + [i+1,n-1] is our answer\n\n\n# Complexity\n- Time complexity:\nO(n) -- sliding window\n\n- Space complexity:\nO(n) -- for prefix and suffix array\n\n# Code\n```\nclass Solution {\npublic:\n int maximizeWin(vector<int>& A, int k) {\n int ans = 0,n = A.size();\n //pointer to start of sliding window\n int start = 0 ;\n //variable for storing current count\n int count = 0;\n //end_limit of range\n int end = A[0] + k;\n \n int cur_val = 0;\n vector<int>pref(n),suff(n);\n\n for(int i=0;i<n;++i){\n int cur = A[i];\n //if current element is in range we increment our count\n if(cur<= end){\n count++;\n }\n else{\n //else we move the start of our window to right until current \n //element is in range \n while(cur>end){\n start++;\n end = A[start]+k;\n count--;\n }\n count++;\n }\n cur_val = max(cur_val,count);\n //pref[i] -- it store the max count from [0,i]\n pref[i] = cur_val;\n }\n \n //now for suffix \n start = n-1;\n end = A[n-1] - k;\n count = 0,cur_val = 0;\n\n for(int i=n-1;i>=0;--i){\n int cur = A[i];\n //if current value is in range \n if(cur>=end){\n count++;\n }\n else{\n //else we move the start of our window to left until current \n //element is in range (we are starting form end and moving to first so left movment)\n while(cur<end){\n start--;\n end = A[start]-k;\n count--;\n }\n count++;\n \n }\n cur_val = max(cur_val,count);\n //suff[i] -- it store the max count from [i,n-1]\n suff[i] = cur_val;\n }\n \n for(int i=0;i<n;++i){\n int sum = pref[i];\n if((i+1)<n)sum += suff[i+1];\n\n //the max sum from [0,i] + [i+1,n-1]\n ans = max(ans,sum);\n }\n \n \n return ans;\n }\n};\n```\n | 24 | 0 | ['Sliding Window', 'Prefix Sum', 'C++'] | 3 |
maximize-win-from-two-segments | Why intuitive approach didn't work out (greedy) | why-intuitive-approach-didnt-work-out-gr-so34 | For all those who are thinking why the intuitive greedy approach didn\'t work out, here is a conversation image\n\n | Dr_Mashoor_Gulati | NORMAL | 2023-02-04T20:44:32.982628+00:00 | 2023-02-04T20:44:32.982669+00:00 | 517 | false | For all those who are thinking why the intuitive greedy approach didn\'t work out, here is a conversation image\n\n | 17 | 0 | ['Greedy'] | 1 |
maximize-win-from-two-segments | DP: leftMax + rightMax | dp-leftmax-rightmax-by-hardcracker-0ov1 | Intuition\nFor every index i, if we can get leftMax[i-1] and rightMax[i], we can iterate through i and get the max result.\n\nleftMax[i]: max on the left of ind | hardcracker | NORMAL | 2023-02-04T16:47:05.894500+00:00 | 2023-02-04T16:58:58.722739+00:00 | 1,431 | false | # Intuition\nFor every index ```i```, if we can get ```leftMax[i-1]``` and ```rightMax[i]```, we can iterate through ```i``` and get the max result.\n\n```leftMax[i]```: max on the left of index ```i``` (including ```i```) \n```rightMax[i]```: max on the right of index ```i``` (including ```i```)\n\nTo get ```leftMax[i]```: the max between ```leftMax[i-1]```, and the number in the window of size ```k``` from ```i``` to the left, i.e., ```i - j + 1```, where ```j``` is the most left element meeting the window size ```k``` requirement for ```i```.\n\nTo get ```rightMax[i]```: the max between ```rightMax[i+1]```, and the number in the window of size ```k``` from ```i``` to the right, i.e., ```j - i + 1```, where ```j``` is the most right element meeting the window size ```k``` requirement for ```i```.\n\nTime complexity: ```O(n)```\n- ```O(n)``` to get ```leftMax```\n- ```O(n)``` to get ```rightMax```\n- ```O(n)``` to get result\n\n# Code\n```\nclass Solution {\n public int maximizeWin(int[] prizePositions, int k) {\n int n = prizePositions.length;\n int[] leftMax = new int[n], rightMax = new int[n];\n // leftMax[i]: max on the left of i (including i) \n // rightMax[i]: max on the right of i (including i)\n\n int j = 0;\n leftMax[0] = 1;\n for(int i = 1; i < n; i++) {\n while (prizePositions[i] - prizePositions[j] > k) j++;\n leftMax[i] = Math.max(leftMax[i - 1], i - j + 1);\n // leftMax[i]: the max between leftMax[i-1], and\n // the number in the window of size k from i to the left\n }\n \n j = n - 1;\n rightMax[n - 1] = 1;\n for(int i = n - 2; i >= 0; i--) {\n while (prizePositions[j] - prizePositions[i] > k) j--;\n rightMax[i] = Math.max(rightMax[i + 1], j - i + 1);\n // rightMax[i]: the max between rightMax[i+1], and\n // the number in the window of size k from i to the right\n }\n \n int result = 0;\n \n for(int i = 0; i <= n; i++) {\n // XXXXXXXXXX i-1 i XXXXXXXXXXX for each i to get leftMax[i - 1] + rightMax[i]\n // edge cases: when i = 0 no leftMax, when i = n - 1 no rightMax\n result = Math.max(result, (i == 0 ? 0 : leftMax[i - 1]) + (i == n ? 0 : rightMax[i]));\n }\n \n return result;\n }\n}\n``` | 17 | 0 | ['Java'] | 1 |
maximize-win-from-two-segments | Catch Up | catch-up-by-votrubac-wueo | We can run the first [l1, r1] and the second [l2, r2] sliding windows at the same time.\n\nAs r2 < l1, the second window catches up as the first one moves.\n\nW | votrubac | NORMAL | 2023-02-07T06:50:47.563104+00:00 | 2023-02-07T06:50:47.563146+00:00 | 796 | false | We can run the first `[l1, r1]` and the second `[l2, r2]` sliding windows at the same time.\n\nAs `r2 < l1`, the second window catches up as the first one moves.\n\nWe track the maximum win we can get from the second window (`max_w2`) so far.\n\nThe win from the first window is `w1`, and we return the best result we can get from `w1 + max_w2`.\n\n**C++**\n```cpp\nint maximizeWin(vector<int>& p, int k) {\n int res = 0, w1 = 0, w2 = 0, max_w2 = 0;\n for (int l1 = 0, r1 = 0, l2 = 0, r2 = 0; r1 < p.size(); ++r1) {\n ++w1;\n for(; p[r1] - p[l1] > k; ++l1)\n --w1;\n for(; r2 < l1; ++r2) {\n ++w2;\n for (; p[r2] - p[l2] > k; ++l2)\n --w2;\n max_w2 = max(max_w2, w2);\n }\n res = max(res, w1 + max_w2);\n }\n return res;\n}\n``` | 12 | 0 | ['C'] | 1 |
maximize-win-from-two-segments | [Python] Binary Search + DP | python-binary-search-dp-by-himanshu3889-mxbs | \n def maximizeWin(self, arr: List[int], k: int) -> int:\n n = len(arr)\n best = [0]*(n+1) # best segment after >= i \n | Himanshu3889 | NORMAL | 2023-02-04T16:16:25.537039+00:00 | 2023-02-08T13:42:04.409787+00:00 | 1,063 | false | \n def maximizeWin(self, arr: List[int], k: int) -> int:\n n = len(arr)\n best = [0]*(n+1) # best segment after >= i \n res = 0\n for i in range(n-1,-1,-1): # curr seg start at ith\n e = bisect.bisect_right(arr,arr[i]+k) # take maximum as possible\n res = max(res,e-i + best[e]) # maximize the segments , curr seg [i,e) + next segment after >= e\n best[i] = max(best[i+1],e-i) # track the best segment [i,e)\n return res | 12 | 1 | ['Dynamic Programming', 'Binary Tree'] | 1 |
maximize-win-from-two-segments | c++ solution dp memoization | c-solution-dp-memoization-by-dilipsuthar-tc3d | \nclass Solution {\npublic:\n long long range=0;\n long long n;\n long long dp[100500][3];\n int find(vector<int>&nums,int index,int count)\n {\n | dilipsuthar17 | NORMAL | 2023-02-04T17:35:12.076352+00:00 | 2023-02-04T17:35:12.076386+00:00 | 1,483 | false | ```\nclass Solution {\npublic:\n long long range=0;\n long long n;\n long long dp[100500][3];\n int find(vector<int>&nums,int index,int count)\n {\n if(count==0||index>=n)\n {\n return 0;\n }\n if(dp[index][count]!=-1)\n {\n return dp[index][count];\n }\n long long ans=find(nums,index+1,count);\n long long it=upper_bound(nums.begin(),nums.end(),nums[index]+range)-nums.begin();\n ans=max(ans,it-index+find(nums,it,count-1));\n return dp[index][count]= ans;\n }\n int maximizeWin(vector<int>& prizePositions, int k) \n {\n memset(dp,-1,sizeof(dp));\n n=prizePositions.size();\n range=k;\n return find(prizePositions,0,2);\n }\n};\n``` | 10 | 0 | ['Dynamic Programming', 'Memoization', 'C', 'C++'] | 0 |
maximize-win-from-two-segments | C++ | | DP+BS | | Memoization | | Well Explained Code | c-dpbs-memoization-well-explained-code-b-ue24 | Intuition\nWe will be going through all the possible combinations of windows and return the max sum.The code will be making sure that the windows don\'t overlap | H_Dabas02 | NORMAL | 2023-02-05T05:23:33.947690+00:00 | 2023-02-05T05:25:01.032953+00:00 | 745 | false | # Intuition\nWe will be going through all the possible combinations of windows and return the max sum.The code will be making sure that the windows don\'t overlap.We will be traversing from right to left as it\'ll allow us to apply binary search to find the start of the window whose end is \'Arr[i]\'\n\n# Approach\n->Start traversing from right to left.\n->At each index make decisions to include the window that\'ll be formed here(End at Arr[i]) or not.\n->In case of exclusion we simply move to next index(i-1).\n->In case of inclusion we have to find the start of the window by binary search (lower bound of Arr[i]-k).The length of the window will be i-idx+1(idx is start of the window) and now to avoid overlapping we simply passs idx-1 to the next call and add the window length and decrement the X variable in next call(X variable denotes the number of windows selected so far)\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int Help(int i,int X,vector<int> &prizePositions,int k,vector<vector<int>> &dp)\n {\n if(X==0)//2 windows have been formed\n {\n return 0;\n }\n if(i<0)//Invalid case(2 windows weren\'t formed)\n {\n return INT_MIN;\n }\n if(dp[i][X]!=-1)\n {\n return dp[i][X];\n }\n\n int exc=Help(i-1,X,prizePositions,k,dp);//exclusion case\n int inc;//inclusion case\n int idx=lower_bound(prizePositions.begin(),prizePositions.end(),prizePositions[i]-k)-prizePositions.begin();//To find the start of this window\n inc=(i-idx+1)+Help(idx-1,X-1,prizePositions,k,dp);\n\n return dp[i][X]=max(inc,exc);\n }\n\n int maximizeWin(vector<int>& prizePositions, int k)\n {\n int n=prizePositions.size();\n if(2*k>=prizePositions[n-1]-prizePositions[0])//If combined length is greater than the range we can cover all prizes\n {\n return n;\n } \n vector<vector<int>> dp(n+1,vector<int> (3,-1));\n return Help(prizePositions.size()-1,2,prizePositions,k,dp);\n }\n};\n``` | 7 | 0 | ['Binary Search', 'Dynamic Programming', 'Memoization', 'C++'] | 2 |
maximize-win-from-two-segments | Simple dp solution with explanation | simple-dp-solution-with-explanation-by-s-dd8b | Intuition\nLet\'s start with a simple problem with one segment. This problem could be solved with a sliding window. To solve the problem with 2 segments we can | svolkovichs | NORMAL | 2023-02-05T23:45:01.906452+00:00 | 2023-02-05T23:45:01.906484+00:00 | 350 | false | # Intuition\nLet\'s start with a simple problem with one segment. This problem could be solved with a sliding window. To solve the problem with 2 segments we can use dynamic programming.\n\n# Approach\nLet\'s define a dp[k] as the max segment in the first k elements. We can iterate an array and for every, i build a max possible segment ending on the ith element. Imagine for particular i we have have segment starting on j. In this case, segment length would be `i - j + 1`. dp[i+1] - max possible segment in the array up to index i. We can calculate `dp[i+1] = max(dp[i], i + j - 1)`. If we have some valid segment from j to i, then a max of 2 segments including this one will be a max segment in the first j elements + length of current segment - `dp[j] + (i - j + 1)`. The final answer for this problem will be `max(dp[j] + (i - j + 1))` for every possible i.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n```\n/**\n * @param {number[]} prizePositions\n * @param {number} k\n * @return {number}\n */\nvar maximizeWin = function(prizePositions, k) {\n const n = prizePositions.length;\n let dp = new Array(n + 1).fill(0);\n let j = 0;\n let res = 0;\n for(let i = 0; i < n; i++) {\n while(prizePositions[i] > prizePositions[j] + k){\n j++;\n }\n let len = i - j + 1;\n dp[i + 1] = Math.max(dp[i], len);\n res = Math.max(res, dp[j] + len);\n }\n \n return res;\n};\n\n\n``` | 6 | 0 | ['Dynamic Programming', 'JavaScript'] | 0 |
maximize-win-from-two-segments | C++ O(N) || Sliding Window || DP | c-on-sliding-window-dp-by-abhay5349singh-ewqb | Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\n\nclass Solution {\npublic:\n int maximizeWin(vector<int>& prizePositions, int k) | abhay5349singh | NORMAL | 2023-08-01T11:19:23.150725+00:00 | 2023-08-01T11:19:23.150749+00:00 | 284 | false | **Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n```\nclass Solution {\npublic:\n int maximizeWin(vector<int>& prizePositions, int k) {\n int n=prizePositions.size();\n \n int i=0, j=0;\n \n // maximum no. of prizes which can be selected for segment [0,j] within range k\n vector<int> l2r(n,0); \n while(j<n){\n while(prizePositions[j] - prizePositions[i] > k) i++;\n \n if(j>0) l2r[j] = l2r[j-1];\n l2r[j] = max(l2r[j],j-i+1);\n \n j++;\n }\n \n // maximum no. of prizes which can be selected for segment [j,n-1] within range k\n vector<int> r2l(n,0);\n i=n-1, j=n-1;\n while(j>=0){\n while(prizePositions[i] - prizePositions[j] > k) i--;\n \n if(j<n-1) r2l[j] = r2l[j+1];\n r2l[j] = max(r2l[j],i-j+1);\n \n j--;\n }\n \n int ans=1;\n for(int i=0;i<n-1;i++) ans=max(ans,l2r[i]+r2l[i+1]);\n \n return ans;\n }\n};\n```\n\n**Do upvote if it helps:)** | 5 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximize-win-from-two-segments | Please help me find error in this code | please-help-me-find-error-in-this-code-b-wb3u | My thought process was- first find the subarray in which the count of prizes is max for a given k.. then remove those elements already picked and repeat the sam | rUdy_c0des | NORMAL | 2023-02-04T17:23:39.936536+00:00 | 2023-02-04T17:23:39.936573+00:00 | 370 | false | My thought process was- first find the subarray in which the count of prizes is max for a given k.. then remove those elements already picked and repeat the same process for 1 more time on the new array since there should be exactly 2 segments.. the code I wrote is as follows- (It passed 61 out of 65 test cases during the contest)\n```\nclass Solution {\n public int maximizeWin(int[] pos, int k) {\n int n = pos.length;\n \n long max1=Long.MIN_VALUE, sum=0;\n int maxIdx=0, i=0,j=0, maxIdx2=0;\n \n while(i<n){\n while(j<n && pos[j]-pos[i] <= k){\n sum++;\n j++;\n }\n if(sum >= max1){\n maxIdx = i;\n max1 = sum;\n maxIdx2 = j;\n }\n while(i<n-1 && pos[i] == pos[i+1]){\n i++;\n sum--;\n }\n i++;\n sum--;\n }\n //System.out.println(max1);\n int[] npos = new int[n-(maxIdx2-maxIdx)];\n int idx=0;\n \n for(i=0; i<maxIdx; i++) npos[idx++] = pos[i];\n for(i=maxIdx2; i<n; i++) npos[idx++] = pos[i];\n n = npos.length;\n //System.out.println(npos[0]);\n long max2=Long.MIN_VALUE;\n i=0;\n j=0;\n sum=0;\n while(i<n){\n while(j<n && npos[j]-npos[i] <= k){\n sum++;\n j++;\n }\n if(sum >= max2){\n max2 = sum;\n }\n while(i<n-1 && npos[i] == npos[i+1]){\n i++;\n sum--;\n }\n i++;\n sum--;\n }\n \n return (int)(max1+max2);\n \n }\n} | 5 | 0 | ['Java'] | 3 |
maximize-win-from-two-segments | Using Binary Search || Easy To understand 🌟 | using-binary-search-easy-to-understand-b-htfe | Approach\nFind the Most appropriate value from all index\'s and pick that value and maximum of remaining values as answer.\nFind same thing for all 1<=i<=n.\n\n | Sriyansh2001 | NORMAL | 2023-02-04T18:15:45.063255+00:00 | 2023-02-04T18:15:45.063282+00:00 | 1,511 | false | # Approach\nFind the Most appropriate value from all index\'s and pick that value and maximum of remaining values as answer.\nFind same thing for all 1<=i<=n.\n\n# Complexity\n- Time complexity:\n O(N LogN)\n\n- Space complexity:\n O(2N)\n\n# Code\n```\nclass Solution {\npublic:\n int lower(vector<int> &v,int val) {\n int i=0,j=v.size()-1,ans=-1;\n while(i<=j) {\n int mid=(i+j)/2;\n if(v[mid]<=val) {\n ans=mid;\n i=mid+1;\n }\n else j=mid-1;\n } return ans;\n }\n\n int maximizeWin(vector<int>& p, int k) {\n int n = p.size();\n vector<int> ans(n);\n for(int i=0 ; i<n ; ++i) {\n ans[i]=lower(p,p[i]+k)-i+1;\n }\n vector<int> b(n);\n for(int i=n-1 ; i>=0 ; --i) b[i] = max((i==n-1?0:b[i+1]),ans[i]);\n int res=0;\n for(int i=0 ; i<n ; ++i) {\n int extra=0;\n if(i+ans[i]<n) {\n extra=b[i+ans[i]];\n }\n res = max(res,ans[i]+extra);\n }\n return res;\n }\n};\n``` | 4 | 0 | ['Binary Search', 'Dynamic Programming', 'C++'] | 1 |
maximize-win-from-two-segments | Beats 100% by speed and memory, Python simple solution. | beats-100-by-speed-and-memory-python-sim-ta5p | Intuition\nLet\'s iterate through the array and for each position, calculate the count of prizes in the interval if the interval ends at the current position an | stivsh | NORMAL | 2023-02-05T14:19:27.176393+00:00 | 2023-02-05T14:48:44.179967+00:00 | 793 | false | # Intuition\nLet\'s iterate through the array and for each position, calculate the count of prizes in the interval if the interval ends at the current position and store the count and the position in the "intervals" list.\n```\nintervals = [(count of prizes, end pos), (count of prizes, end pos)]\n```\n\nLet\'s also store the interval which covers the maximum count of prizes that ends before some position, the "max stack for the intervals," in the "max_before".\n```\nmax_before = [(max count of prizes, end pos1), (max count of prizes, end pos2)]\nend pos1 <= end pos2 <= end pos3 <= end pos4 ....\ncount1 <= count2 <= count3 <= count4 ...\n```\n\nThe solution is then straightforward and is based on two key ideas:\n\n1. If we have two intervals, we can make them non-intersecting by moving the first of them, as the second will cover the same prizes. So we need only consider the non-intersecting intervals.\n\n2. The solution must have the last interval. To find the solution, we pop intervals from the "intervals" list one by one and calculate the solution if the current interval is the last one. Then, find the maximum among these solutions.\n\nTo implement this, we pop the next interval from the "intervals" list - the current last interval.\nThen, pop all intervals from the "max_before" list that do not end before the current interval.\nThe top of the "max_before" list will then have the interval with the maximum prize count before the current interval.\nThe current best candidate solution for the current last interval is the count of prizes for the current last interval plus the top of the "max_before" interval.\n```\ncandidate = count+(0 if not max_beffore else max_beffore[-1][0])\n```\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n # count of prizes for all intervals\n # (count, end position of interval) \n intervals = []\n # max stack of intervals\n # (count, end position of interval),\n # There can\'t be interval with bigger count before the interval\n max_beffore = []\n start_inx = 0 # start index of the current interval\n count = 0 # count of the current interval\n for inx, pos in enumerate(prizePositions):\n count += 1\n # subtract prizes from the current interval if they are not covered by the interval\n while pos-k > prizePositions[start_inx]:\n count -= 1\n start_inx += 1\n intervals.append((count, pos))\n if not max_beffore or max_beffore[-1][0] < count:\n max_beffore.append((count, pos))\n\n max_solution = 0\n while intervals:\n # the last interval for the current solution\n count, pos = intervals.pop()\n # max_beffore stores only intervals before the last interval,\n # max_beffore is a max stack,\n # so the top of the max possible has the max count among all values in the max_beffore\n while max_beffore and max_beffore[-1][1] >= pos-k:\n max_beffore.pop()\n # The soluthon if the current last interval is the last\n candidate = count+(0 if not max_beffore else max_beffore[-1][0])\n # we need to find maximum among all candidates\n max_solution = max(candidate, max_solution)\n return max_solution\n \n``` | 3 | 0 | ['Python3'] | 0 |
maximize-win-from-two-segments | C++ || Maintain 2 arrays, front and back, to calculate the answer | c-maintain-2-arrays-front-and-back-to-ca-nwwf | In the solution, what I have tried to do is to have 2 arrays which store, for each index i, for the front array, the value stored in array tells us about the ma | pranjal_gaur | NORMAL | 2023-02-05T04:51:19.242543+00:00 | 2023-02-05T04:51:19.242569+00:00 | 163 | false | In the solution, what I have tried to do is to have 2 arrays which store, for each index i, for the front array, the value stored in array tells us about the maximum window that can satisfy the given condition of k, and similarily for the back row, the values tell us about the maximum window size that satisfies the given condition.\n\nAnd, after we have calculated both front and back array, we just traverse from 0 to n-1 and use both these arrays to find 2 windows as required in the question.\n\n```\n\tint maximizeWin(vector<int>& arr, int k) {\n int ans = 0, n = arr.size();\n if(n==1) return 1;\n \n vector<int> fr(n, 0), bk(n, 0);\n int i=0, j=0, mx = 1;\n while(j<n) {\n while(j>=i && arr[j]-arr[i] > k) i++;\n mx = max(j-i+1, mx);\n fr[j] = mx;\n j++;\n }\n \n j=n-1, i=n-1, mx = 1;\n while(j>=0) {\n mx = max(i-j+1, mx);\n bk[j] = mx;\n while(j<=i && arr[i]-arr[j] > k) i--;\n j--;\n }\n \n for(int i=0;i<n;i++) {\n ans = max(ans, fr[i]+bk[i]-1);\n }\n \n return ans;\n } | 3 | 0 | ['C'] | 0 |
maximize-win-from-two-segments | python3 Solution | python3-solution-by-motaharozzaman1996-m3xj | \n\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n dp=[0]*(len(prizePositions)+1)\n res=0\n j=0\n | Motaharozzaman1996 | NORMAL | 2023-02-04T16:35:25.866459+00:00 | 2023-02-04T16:35:25.866507+00:00 | 415 | false | \n```\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n dp=[0]*(len(prizePositions)+1)\n res=0\n j=0\n for i,a in enumerate(prizePositions):\n while prizePositions[j]<prizePositions[i]-k:\n j+=1\n dp[i+1]=max(dp[i],i-j+1)\n res=max(res,i-j+1+dp[j])\n \n return res \n \n \n \n``` | 3 | 1 | ['Python', 'Python3'] | 0 |
maximize-win-from-two-segments | Map Intuitive Approach!! | map-intuitive-approach-by-the_arc_knight-4qqd | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | the_arc_knight_24 | NORMAL | 2023-02-04T16:18:26.788505+00:00 | 2023-02-04T16:18:26.788537+00:00 | 1,205 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int func(vector<int>& v, int l, int r) {\n return upper_bound(v.begin(), v.end(), r) - lower_bound(v.begin(), v.end(), l);\n }\n \n int maximizeWin(vector<int>& v, int k) {\n map<int, int> ma;\n for(auto it : v) {\n ma[it]++;\n }\n vector<int> w;\n for(auto it : ma) {\n w.push_back(it.first);\n }\n int n = w.size();\n int maxi = 0;\n int maxi_prev = 0;\n for(int i = n - 1; i >= 0; i--) {\n maxi = max(maxi, maxi_prev + func(v, w[i] - k, w[i]));\n maxi_prev = max(maxi_prev, func(v, w[i], w[i] + k));\n }\n return maxi;\n }\n};\n\n``` | 3 | 1 | ['C++'] | 2 |
maximize-win-from-two-segments | Python Solution Using Binary Search | python-solution-using-binary-search-by-n-arrb | For More DSA concepts and problem solution subscribe my channel\nhttps://www.youtube.com/channel/UCPbJzXhXAPB3aQnrBcbnqgQ\n# Code\n\nfrom bisect import bisect_r | ng2203 | NORMAL | 2023-02-25T04:51:43.618135+00:00 | 2024-04-13T19:52:43.070543+00:00 | 136 | false | ### For More DSA concepts and problem solution subscribe my channel\nhttps://www.youtube.com/channel/UCPbJzXhXAPB3aQnrBcbnqgQ\n# Code\n```\nfrom bisect import bisect_right,bisect_left\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n ans=prv=0\n for i,item in enumerate(prizePositions):\n j1=bisect_left(prizePositions,item-k)\n j2=bisect_right(prizePositions,item+k)\n ans=max(ans,j2-j1,prv+j2-i)\n prv=max(prv,i-j1+1)\n return ans\n``` | 2 | 0 | ['Python3'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.