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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
search-suggestions-system | [Python 3] Binary Search | python-3-binary-search-by-sb26-xz7y | \'\'\'\n\tdef suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \n \n products.sort()\n \n | sb26 | NORMAL | 2020-07-11T23:02:02.510718+00:00 | 2020-07-11T23:02:02.510762+00:00 | 623 | false | \'\'\'\n\tdef suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \n \n products.sort()\n \n s=\'\'\n ans=[]\n \n \n def bin_search(array,word):\n lo=0\n hi=len(array)\n \n while lo<hi:\n \n mid = (lo+hi)//2\n \n if array[mid]<word:\n lo = mid+1\n else:\n hi = mid\n \n return lo\n \n \n for ch in searchWord:\n s=s+ch\n l = len(s)\n temp_arry=[]\n \n index = bin_search(products,s)\n \n for i in range(index,min(len(products),index+3)):\n if products[i][0:l]==s:\n \n temp_arry.append(products[i])\n \n ans.append(temp_arry)\n \n return ans\n \n \'\'\' | 5 | 0 | ['Binary Search', 'Python', 'Python3'] | 3 |
search-suggestions-system | Java 96% fast with explanation | java-96-fast-with-explanation-by-anjali1-luqt | If you found the solution interesting, kindly upvote. :)\n\n\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String search | anjali100btcse17 | NORMAL | 2020-07-03T12:07:30.403190+00:00 | 2020-07-03T12:07:30.403226+00:00 | 350 | false | If you found the solution interesting, kindly upvote. :)\n\n```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n \tList<List<String>> res= new ArrayList<List<String>>();\n \tint low=0, high= products.length-1;\n \tint min=0;\n \tArrays.sort(products);\t//Sorting in lexically increasing order\n \tfor(int i=0; i<searchWord.length(); i++)\n \t{\n \t\t//Checking from the low side\n \t\twhile((low <= high) &&(products[low].length() <= i || \n \t\t\t\tproducts[low].charAt(i) != searchWord.charAt(i)))\n \t\t\tlow++;\t//if the character does not match, we do not need to search that word\n \t\t\n \t\t//Checking from the end side\n \t\twhile((low <= high ) && (products[high].length() <= i || \n \t\t\t\tproducts[high].charAt(i) != searchWord.charAt(i)))\n \t\t\thigh--;\t//if the character does not match, we do not need to search that word\n \t\t\n \t\t\n \t\t//After this is done, we will have our search from low+3 (as we can choose only 3 words maximum)\n \t\t//And it can only go upto high+1 maximum\n \t\tmin= Math.min(low+3, high+1);\n \t\t\n \t\t//Adding to the results now\n \t\tList<String> temp= new ArrayList<String>();\n \t\tfor(int j=low; j<min; j++)\n \t\t{\n \t\t\ttemp.add(products[j]);\n \t\t}\n \t\tres.add(temp);\n \t}\n \t\n \treturn res;\n }\n}\n``` | 5 | 0 | [] | 1 |
search-suggestions-system | [Python] 5 lines, just short | python-5-lines-just-short-by-rkys-18l2 | \nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n ans, products = [], sorted(products)\n | rkys | NORMAL | 2020-02-14T05:18:24.283284+00:00 | 2020-02-14T05:18:24.283321+00:00 | 414 | false | ```\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n ans, products = [], sorted(products)\n for i in range(len(searchWord)):\n products = [p for p in products if i < len(p) and searchWord[i] == p[i]]\n ans.append(products[:3])\n return ans\n``` | 5 | 0 | ['Python'] | 1 |
search-suggestions-system | Simple and Easy JAVA Solution | simple-and-easy-java-solution-by-imranan-0r6l | \nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n Arrays.sort(products);\n \n L | imranansari | NORMAL | 2020-02-10T09:38:19.561086+00:00 | 2020-02-10T09:38:55.441841+00:00 | 476 | false | ```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n Arrays.sort(products);\n \n List<List<String>> res = new ArrayList<>();\n for (int i = 0; i < searchWord.length(); i++) {\n String word = searchWord.substring(0,i+1);\n List<String> list = new ArrayList<>();\n for (String product : products) {\n if (product.length() < word.length())\n continue;\n if (list.size() >= 3)\n break;\n String sub = product.substring(0,i+1);\n if (word.equals(sub))\n list.add(product);\n }\n\n res.add(list);\n }\n \n return res;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
search-suggestions-system | python, Time: O(mnlog(n)) [99.9%], Space: O(1) [100.0%], squeeze, clean, full comment | python-time-omnlogn-999-space-o1-1000-sq-d04f | Complexity Analysis:\nTime: O(mnlog(n)+m+n), can be simplify as O(mnlog(n))\nSpace: O(1) [100.0%]\nWhere:\n m: max length among len(searchWord) and products\n n | chumicat | NORMAL | 2019-11-28T05:42:21.842462+00:00 | 2019-12-02T10:22:25.072821+00:00 | 1,230 | false | ## Complexity Analysis:\nTime: O(mnlog(n)+m+n), can be simplify as O(mnlog(n))\nSpace: O(1) [100.0%]\nWhere:\n* m: max length among len(searchWord) and products\n* n: len(products)\n* ret space is not included\n\nSince it useing sorting, Time complexity = sort times*each check complexity = nlog(n) * m\n\n```python\n# Dev: Chumicat\n# Date: 2019/11/28\n# Submission: https://leetcode.com/submissions/detail/282213232/\n# (Time, Space) Complexity : O(mnlog(n)), O(1)\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n """\n :type products: List[str]\n :type searchWord: str\n :rtype: List[List[str]]\n """\n # After sort, product list will follow alphabetic order\n products.sort()\n \n # Use two iter to hold the target words between\n start, end, ret = 0, len(products)-1, []\n for n_th, c in enumerate(searchWord):\n # Check between start and end to prevent unusable move\n # Check lenth of current "product string" to prevent "search word" longer than "product string"\n while start <= end and (products[start][n_th] < c if len(products[start])>n_th else True):\n start += 1\n while start <= end and (products[end][n_th] > c if len(products[end])>n_th else True):\n end -= 1\n \n # Append at most three element array\n ret.append(products[start:start+3] if end > start+1 else products[start:end+1])\n return ret\n``` | 5 | 0 | ['Python', 'Python3'] | 2 |
search-suggestions-system | JavaScript simple solution | javascript-simple-solution-by-yyoon-948i | ```\nvar suggestedProducts = function(products, searchWord) {\n products.sort();\n let i = 1;\n let answers = [];\n while (i <= searchWord.length) { | yyoon | NORMAL | 2019-11-24T04:49:04.959772+00:00 | 2019-11-24T04:49:04.959831+00:00 | 343 | false | ```\nvar suggestedProducts = function(products, searchWord) {\n products.sort();\n let i = 1;\n let answers = [];\n while (i <= searchWord.length) {\n let sw = searchWord.substring(0, i);\n let tmp = products.filter(p => p.substring(0,i) === sw);\n if (tmp.length > 3) tmp.length = 3;\n answers.push(tmp);\n i++\n }\n\n return answers;\n}; | 5 | 0 | [] | 1 |
search-suggestions-system | [C++] Trie Method | c-trie-method-by-orangezeit-8vwq | UPDATE\nSince we only have lowercase letters, the following codes could be slightly improved by using\n\n\nstruct TrieNode {\n int nums;\n vector<TrieNode | orangezeit | NORMAL | 2019-11-24T04:02:56.544029+00:00 | 2019-11-24T05:53:58.003474+00:00 | 562 | false | **UPDATE**\nSince we only have lowercase letters, the following codes could be slightly improved by using\n\n```\nstruct TrieNode {\n int nums;\n vector<TrieNode*> m;\n TrieNode(): nums(0) { m.resize(26); }\n};\n```\nsince vector has a simpler underlying structure in STL. However, map is more scalable if the number of characters is unknown.\n\n```\nstruct TrieNode {\n int nums;\n map<char, TrieNode*> m;\n TrieNode(): nums(0) {}\n};\n\nclass Solution {\npublic:\n TrieNode* tn = new TrieNode();\n \n void buildTrie(const vector<string>& products) {\n for (const string& str: products) {\n TrieNode* temp = tn;\n for (const char& c: str) {\n if (!temp->m.count(c))\n temp->m[c] = new TrieNode();\n temp = temp->m[c];\n }\n temp->nums++;\n }\n }\n \n void findWords(string& word, vector<string>& words, TrieNode* node) {\n if (words.size() >= 3) return;\n if (node->nums)\n for (int i = 1; i <= node->nums; ++i)\n words.push_back(word);\n for (const auto& p: node->m) {\n word += p.first;\n findWords(word, words, p.second);\n word.pop_back();\n }\n }\n \n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n buildTrie(products);\n TrieNode* temp = tn;\n vector<vector<string>> ans(searchWord.length());\n int k(0);\n string prefix;\n \n for (const char& c: searchWord) {\n if (temp->m.count(c)) {\n prefix += c;\n temp = temp->m[c];\n vector<string> words;\n findWords(prefix, words, temp);\n if (words.size() > 3) words.resize(3);\n ans[k++] = words;\n } else {\n break;\n }\n }\n \n return ans;\n }\n};\n``` | 5 | 2 | ['Trie'] | 4 |
search-suggestions-system | Very Easy using Linq on C# | very-easy-using-linq-on-c-by-daviti-yz1c | \npublic IList<IList<string>> SuggestedProducts(string[] products, string searchWord)\n {\n var filteredProducts = products.OrderBy(prod=>prod | daviti | NORMAL | 2019-11-24T04:01:18.650129+00:00 | 2019-11-24T04:01:18.650167+00:00 | 674 | false | ```\npublic IList<IList<string>> SuggestedProducts(string[] products, string searchWord)\n {\n var filteredProducts = products.OrderBy(prod=>prod).ToList();\n var resList = new List<IList<string>>();\n for (int len = 1; len <= searchWord.Length; len++)\n {\n string str = searchWord.Substring(0, len);\n filteredProducts = filteredProducts.Where(prod => prod.StartsWith(str)).ToList();\n resList.Add(filteredProducts.Take(3).ToList());\n }\n\n return resList;\n }\n``` | 5 | 1 | [] | 1 |
search-suggestions-system | Java Bruteforce 99% faster 😁 | java-bruteforce-99-faster-by-deleted_use-cm4s | Intuition\nThe problem is about suggesting products based on a search word. To find the best suggestions, we need to sort the list of products alphabetically, t | deleted_user | NORMAL | 2024-04-20T21:59:09.420830+00:00 | 2024-04-20T21:59:09.420871+00:00 | 825 | false | # Intuition\nThe problem is about suggesting products based on a search word. To find the best suggestions, we need to sort the list of products alphabetically, then for each prefix derived from the search word, identify the products that start with that prefix.\n# Approach\nSorting Products: Begin by sorting the array of products. This allows us to use a two-pointer technique for efficient prefix matching.\nTwo-Pointer Approach:\nMaintain two pointers (left and right) to represent the current range of products matching a prefix.\nAs we move through the characters in the search word, adjust the pointers to shrink the range to products matching the current prefix.\nIf the current product doesn\'t meet the prefix criteria, increment left or decrement right.\nAdding Suggestions: For each prefix, gather up to three products starting with that prefix from the current range and add them to the results.\nTo optimize, ensure that left is not greater than right to avoid invalid ranges.\nReturn the Result: Finally, return the list of suggestions generated for each prefix in the search word.\n# Complexity\nTime complexity:\n\nSorting the products is O(n log n). The loop for each character in the search word requires adjusting the two pointers, leading to a worst-case time complexity of O(m \xD7 n), where m is the length of the searchWord and n is the number of products. Thus, the overall time complexity is O(n log n + m \xD7 n).\n\nSpace complexity:\n\nThe space used is proportional to the result list and intermediate lists, resulting in O(m \xD7 k), where m is the length of the searchWord and k is the maximum number of suggestions for each prefix (typically 3).\n# Code\n```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n Arrays.sort(products);\n List<List<String>> result = new ArrayList<>();\n int left = 0, right = products.length - 1;\n for (int i = 0; i < searchWord.length(); i++) {\n char currentChar = searchWord.charAt(i);\n while (left <= right && (products[left].length() <= i || products[left].charAt(i) != currentChar)) {\n left++;\n }\n while (left <= right && (products[right].length() <= i || products[right].charAt(i) != currentChar)) {\n right--;\n }\n List<String> suggestions = new ArrayList<>();\n for (int j = left; j < Math.min(left + 3, right + 1); j++) {\n suggestions.add(products[j]);\n }\n result.add(suggestions);\n }\n return result;\n }\n}\n\n``` | 4 | 0 | ['Java'] | 0 |
search-suggestions-system | C++ || Intuitive Trie Solution || Beats 75% | c-intuitive-trie-solution-beats-75-by-sh-pgle | Intuition\nSince the problem involves strings and prefixes, my immediate thought was to implement a solution using Trie. We can store each word in the trie and | shobhitkumar43 | NORMAL | 2023-09-07T22:57:05.721953+00:00 | 2023-09-07T22:57:31.403726+00:00 | 662 | false | # Intuition\nSince the problem involves strings and prefixes, my immediate thought was to implement a solution using Trie. We can store each word in the trie and for each prefix also store the words for which it acts as a prefix.\n\n# Approach\nWe implement a basic Trie data structure with additional vector of strings to store all the words for which the current trie node is a prefix to. Now while inserting a word into the trie we will push each visited node into a stack and after inserting the word, we will pop out the nodes and push the word into their works vector.\n\nNow when we traverse through the searchWord, we only need to add the vector words for each of the prefixes to the final answer while also checking if the prefix exists in the trie or not.\n\n# Complexity\n- Time complexity:\nO(NlogN) due to sorting\n\n- Space complexity:\nO(N)\n\n# Code\n```\nstruct Node{\n Node* links[26];\n bool flag = false;\n vector<string>words;\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};\nclass Solution {\npublic:\n void insert(Node* trie,string word,stack<Node*>&st){\n st.push(trie);\n for(int i=0;i<word.length();i++){\n if(!trie->containsKey(word[i])){\n trie->put(word[i],new Node());\n }\n trie = trie->get(word[i]);\n st.push(trie);\n }\n trie->setEnd();\n }\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n vector<vector<string>>ans(searchWord.length());\n sort(products.begin(),products.end());\n Node* trie = new Node();\n for(auto word:products){\n stack<Node*>st;\n insert(trie,word,st);\n while(!st.empty()){\n Node* temp = st.top();\n st.pop();\n if(temp->words.size()<3)temp->words.push_back(word);\n }\n }\n for(int i=0;i<searchWord.length();i++){\n if(!trie->containsKey(searchWord[i])){\n return ans;\n }\n trie = trie->get(searchWord[i]);\n ans[i]=trie->words;\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['String', 'Trie', 'C++'] | 2 |
search-suggestions-system | Trie Implementation | C++ | Easy Solution | trie-implementation-c-easy-solution-by-j-yzz4 | Intuition\nTrie(prefix-tree) data structure is standard type of data structure for solving dictionary related problems.\n Describe your first thoughts on how to | Jeetaksh | NORMAL | 2023-06-12T19:53:48.275879+00:00 | 2023-06-12T19:53:48.275900+00:00 | 1,366 | false | # Intuition\nTrie(prefix-tree) data structure is standard type of data structure for solving dictionary related problems.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Create a Trie data structure to store the products.\n- Insert each product into the Trie.\n- Initialize an empty vector of vectors called "res" to store the suggestions.\n- Iterate through each character in the searchWord.\n- Append the character to the prefix string.\n- Retrieve the suggestions for the current prefix using the getwords() function of the Trie.\n- Append the suggestions to the "res" vector.\n- Return the res vector containing the suggestions for each character of the searchWord.\n\n# Complexity\n- Time complexity: O(N + M), where N is the total number of characters in the products array and M is the length of the searchWord.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N), where N is the total number of characters in the products array. \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Trie{\n struct Node{\n bool isWord = false;\n vector<Node*> children{vector<Node*>(26,NULL)};\n } *Root, *curr;\n\n\n void dfs(Node *curr, string &word, vector<string> &ans){\n if(ans.size()==3)return;\n if(curr->isWord)ans.push_back(word);\n\n for(char c=\'a\';c<=\'z\';c++){\n if(curr->children[c-\'a\']){\n word+=c;\n dfs(curr->children[c-\'a\'],word,ans);\n word.pop_back();\n }\n }\n }\n\npublic:\n Trie(){\n Root = new Node;\n }\n\n void insert(string &s){\n curr=Root;\n for(char &c :s){\n if(!curr->children[c-\'a\'])curr->children[c-\'a\']=new Node();\n curr=curr->children[c-\'a\'];\n }\n curr->isWord=true;\n }\n\n vector<string> getwords(string &prefix){\n curr=Root;\n vector<string> res;\n\n for(char &c: prefix){\n if(!curr->children[c-\'a\'])return res;\n curr=curr->children[c-\'a\'];\n }\n dfs(curr,prefix,res);\n return res;\n }\n}; \n\n\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n Trie trie = Trie();\n vector<vector<string>> res;\n for(string &w:products)trie.insert(w);\n string prefix;\n for(char &c:searchWord){\n prefix+=c;\n res.push_back(trie.getwords(prefix));\n } \n return res;\n }\n};\n```\n**Please upvote if it helped. Happy Coding!** | 4 | 0 | ['C++'] | 0 |
search-suggestions-system | ✅EASY TRIE SOLUTION C++ | easy-trie-solution-c-by-amangupta12207-wxfs | Intuition\nInsert All products in trie. And then search for suggestions for each prefix of SearchTerm.\n\n# Code\n\nclass Solution {\npublic:\n struct Node { | Amangupta12207 | NORMAL | 2022-12-18T11:04:13.408981+00:00 | 2022-12-18T11:04:57.246830+00:00 | 576 | false | # Intuition\nInsert All products in trie. And then search for suggestions for each prefix of SearchTerm.\n\n# Code\n```\nclass Solution {\npublic:\n struct 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 };\n class Trie {\n private : Node * root;\n public:\n Trie() {\n root = new Node();\n }\n \n void insert(string word) {\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 is end here mark flag as true \n }\n \n vector<string> Suggestions(string searchWord) {\n Node * node = root;\n int n = searchWord.size(); \n vector<string> suggestions;\n for(int i = 0;i<n;i++){\n if(!node->isContains(searchWord[i])) return suggestions; // if don\'t found match return \n node = node->get(searchWord[i]); // move forward\n }\n int count = 0; // we have to find 3 product having prefix as searchWord\n helper(node,count,searchWord,suggestions); // get suggestion for searchWord using dfs \n // root will be the node where our searchWord ends and curr will be searchword as we already traversed it \n return suggestions;\n }\n void helper(Node * root, int &count, string curr,vector<string>&suggestions){\n if(root == NULL) return;\n if(count == 3) return;\n if(root -> flag == true){ // if found a word push and inc count\n suggestions.push_back(curr);\n count++;\n if(count == 3) return; // just optimisation\n }\n for(char ch = \'a\';ch<=\'z\';ch++){\n if(root->isContains(ch))\n helper(root->get(ch),count,curr+ch, suggestions);\n }\n }\n \n };\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n Trie trie;\n for(auto i : products) trie.insert(i);\n vector<vector<string>> ans;\n int n = searchWord.size();\n for(int i = 0;i<n;i++){\n string curr = searchWord.substr(0,i+1); // search for each search term \n // like for mouse get suggestions for m , mo , mou , mous , mouse\n ans.push_back(trie.Suggestions(curr));\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Trie', 'C++'] | 0 |
search-suggestions-system | Some Leet Code Problem's Java Solutions Based On Tries Data Structure | some-leet-code-problems-java-solutions-b-i50u | 1268 : Search Suggestions System\n1233 : Remove Sub-Folders from the Filesystem\n648\t: Replace Words\n820\t: Short Encoding of Words\n208\t: Implement Trie (Pr | nitwmanish | NORMAL | 2022-10-03T07:11:32.573338+00:00 | 2023-01-27T00:30:51.232332+00:00 | 256 | false | [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)\n[472. Concatenated Words](https://leetcode.com/problems/concatenated-words/discuss/3103462/Java-Solution-or-Using-Trie-or-Runtime-%3A-48-ms-or-beats-91.92)\n | 4 | 0 | ['Tree', 'Trie', 'Java'] | 0 |
search-suggestions-system | Using Trie and why the performance is not good as expected | using-trie-and-why-the-performance-is-no-29lo | I think many of you want to solve this problem with Trie(Prefix Tree) like me. And after we code it out, submit it, we found we need to cost around 10 times tha | cgrieftesla | NORMAL | 2022-06-29T11:13:34.131318+00:00 | 2022-06-29T11:13:34.131351+00:00 | 448 | false | I think many of you want to solve this problem with **Trie(Prefix Tree)** like me. And after we code it out, submit it, we found we need to cost around 10 times than other people\'s brute force way. This time you might be confused, frustrated and want to know why. Here is my analysis.\n\nI import "**time**" to do the analysis. You could run my code, see the time costing of building the Trie and running the search part.\n\nI will share my result. For the example input in the description, the building time is around **1\\*e-4**, and the search part is around **1\\*e-5**.\n\nRegarding to the brute force way, I choose a method that could get the result in Leetcode around 100ms, and that method will give us around **3.5\\*e-5**.\n\nSo that it is clear, building the prefix tree is time costing. But after that search part is more quick than brute force way.\n\nWhen there is a situation that **products** is always still and we are asked to call the **searchWords** many times, it is a better way to build prefix tree firstly and then to search.\n\n\n```\nimport time\nclass TriNode():\n def __init__(self):\n self.children = [None]*26\n self.contain = []\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \n buildstart = time.time()\n root = TriNode()\n for product in products:\n cur = root\n for i in range(len(product)+1):\n if i==len(product):\n cur.contain.append(product)\n break\n if cur.children[ord(product[i])-ord(\'a\')]==None:\n newNode = TriNode()\n cur.children[ord(product[i])-ord(\'a\')] = newNode\n cur = cur.children[ord(product[i])-ord(\'a\')]\n \n \n \n \n def dfs(node):\n res = []\n if node==None:\n return []\n if node.contain:\n res.append(node.contain[0])\n for i in range(26):\n tmp = dfs(node.children[i])\n for item in tmp:\n res.append(item)\n \n node.contain = res.copy()\n return res\n \n dfs(root)\n \n buildend = time.time()\n\n searchstart = time.time()\n \n if searchWord == "":\n return []\n \n res = []\n \n cur = root\n\n for c in searchWord:\n if cur==None:\n res.append([])\n continue\n cur = cur.children[ord(c)-ord(\'a\')]\n tmp = []\n if cur==None:\n res.append([])\n continue\n for i in range(len(cur.contain)):\n if i==3:\n break\n tmp.append(cur.contain[i])\n res.append(tmp.copy())\n searchend = time.time()\n \n print("THis is build time", buildend-buildstart)\n print("This is search time", searchend- searchstart)\n \n return res\n \n \n``` | 4 | 0 | ['Depth-First Search', 'Trie', 'Python'] | 0 |
search-suggestions-system | Search Suggestions System | Without using Trie | Java Solution | search-suggestions-system-without-using-ni97q | \nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new ArrayList<>(); | shaguftashahroz09 | NORMAL | 2022-06-19T16:30:20.433874+00:00 | 2022-06-19T16:30:20.434063+00:00 | 105 | false | ```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new ArrayList<>();\n Arrays.sort(products);\n int l=0,r=products.length-1;\n String start="";\n for(int i=0;i<searchWord.length();i++)\n {\n start += searchWord.charAt(i);\n while(l<=r && l<products.length && !products[l].startsWith(start))\n l++;\n while(r>0 && r>=l && !products[r].startsWith(start))\n r--;\n List<String> suggest = new ArrayList<>();\n for(int j=0;j<3;j++)\n {\n if(((l+j) >= products.length) || (l+j) > r)\n break;\n suggest.add(products[l+j]);\n }\n ans.add(suggest);\n }\n return ans;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
search-suggestions-system | ✅C++ | ✅2 Approaches | ✅Use Binary Search | ✅Efficient Solution | 🗓️ DLC June, Day 19 | c-2-approaches-use-binary-search-efficie-ic10 | Brute-Force:\n\nTC : O(NlogN + NxS^2)\nSc : O(1) - vector> is return type so it is not counted\nHere,\n N : size of products\n S : size of searchedword\n | Yash2arma | NORMAL | 2022-06-19T16:09:17.254007+00:00 | 2022-06-19T16:09:17.254051+00:00 | 489 | false | **Brute-Force:**\n\n**TC : O(NlogN + NxS^2)\nSc : O(1)** - vector<vector<string>> is return type so it is not counted\nHere,\n N : size of products\n S : size of searchedword\n NlogN : For sorting\n NXS^2 : We find S size words in N products and making S size substrings\n\n**Code:**\n```\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) \n {\n sort(products.begin(), products.end()); //sort products to get elements in lexicographical order\n vector<vector<string>> res;\n \n string cur = "";\n for(auto it: searchWord) //cover searchWord letter by letter\n {\n vector<string> suggested;\n cur += it;\n int j=0;\n for(auto product:products) //find cur string in products\n {\n if(j==3) break; //when we suggested 3 products\n \n if(product.substr(0, cur.size()) == cur) //matching cur with product substring\n {\n suggested.push_back(product); //if match push it in suggested\n j++;\n }\n \n }\n res.push_back(suggested); //push vector for cur in res\n }\n return res;\n }\n};\n```\n**Please upvote if it helps**\uD83D\uDE0A\u2764\uFE0F\n\n**Better:**\n\n**TC: O(NlogN x logN)\nSC: O(1)**\nHere,\n NlogN : For sorting\n logN : For each query\n \n**Code:**\n```\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) \n {\n auto it = products.begin(); //staring iterator for products\n sort(it, products.end()); //sort products to get elements in lexicographical order\n vector<vector<string>> res;\n \n string cur = "";\n for (char c : searchWord) //cover searchWord letter by letter\n {\n cur += c;\n vector<string> suggested;\n \n //iterator \'it\' pointing to the first element in the range [it, products.end()) matching with cur\n it = lower_bound(it, products.end(), cur); \n \n for (int i = 0; i < 3 && it + i != products.end(); i++) //for suggesting 3 words\n {\n string& s = *(it + i); //s stores product at it+i index\n if (s.find(cur)) break; //if cur is not found in s we don\'t push s in suggested\n suggested.push_back(s);\n }\n res.push_back(suggested);\n }\n return res;\n }\n};\n```\n\n**Please upvote if it helps**\uD83D\uDE0A\u2764\uFE0F\n | 4 | 0 | ['String', 'C', 'Sorting', 'Binary Tree', 'C++'] | 1 |
search-suggestions-system | Java Solution Using String | java-solution-using-string-by-samarth-kh-cwtz | Approach 1\n\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new Ar | Samarth-Khatri | NORMAL | 2022-06-19T12:41:16.282901+00:00 | 2022-06-19T13:33:21.360141+00:00 | 547 | false | # Approach 1\n```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new ArrayList();\n Arrays.sort(products);\n String subs="";\n for(int i=0;i<searchWord.length();++i){\n List<String> ians = new ArrayList();\n subs += searchWord.charAt(i);\n for(int j=0;j<products.length;++j){\n if(products[j].startsWith(subs)){\n ians.add(products[j]);\n if(ians.size()==3)\n break;\n }\n }\n ans.add(ians);\n }\n return ans;\n }\n}\n```\n\n# Approach 2 -> Binary Search - A lil faster\n```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new ArrayList();\n Arrays.sort(products);\n for(int i=0;i<searchWord.length();++i) {\n List<String> ians = new ArrayList();\n String subs = searchWord.substring(0,i+1); \n int idx = binarySearch(products, subs);\n for(int j=idx;j<products.length;++j) {\n if(products[j].startsWith(subs)) {\n ians.add(products[j]);\n if(ians.size()==3)\n break;\n }\n }\n ans.add(ians);\n }\n return ans;\n }\n \n public int binarySearch(String[] products, String prefix) {\n int left=0, right=products.length-1,mid=0; \n while(left<=right) {\n mid = left + (right-left)/2;\n if (products[mid].compareTo(prefix)>=0) \n right =mid-1;\n else \n left=mid+1;\n }\n return right+1; \n }\n}\n``` | 4 | 0 | ['String', 'Java'] | 1 |
search-suggestions-system | Efficient C++ Solution using binary-search | efficient-c-solution-using-binary-search-nv35 | Please upvote this post if you like my solution/approach.\n\ncpp\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string> &produc | travanj05 | NORMAL | 2022-06-19T10:58:40.066189+00:00 | 2022-07-03T18:20:00.959101+00:00 | 314 | false | Please **upvote** this post if you like my solution/approach.\n\n```cpp\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string> &products, string &searchWord) {\n vector<vector<string>> res;\n sort(products.begin(), products.end());\n int l = 0, r = products.size() - 1;\n for (int i = 0; i < searchWord.size(); i++) {\n char ch = searchWord[i];\n while(l<=r && (products[l].size() <= i || products[l][i]!=ch)) l++;\n while(l<=r && (products[r].size() <= i || products[r][i]!=ch)) r--;\n res.push_back(vector<string>());\n int m = min(3, r - l + 1);\n for (int j = 0; j < m; j++) {\n res.back().push_back(products[l + j]);\n }\n }\n return res;\n }\n};\n``` | 4 | 0 | ['C', 'Binary Tree', 'C++'] | 1 |
search-suggestions-system | Simple Easy Approach | simple-easy-approach-by-vaibhav7860-6uc4 | \nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n product = []\n for i in range(len(s | vaibhav7860 | NORMAL | 2022-06-19T06:19:27.858930+00:00 | 2022-06-19T06:19:27.858970+00:00 | 949 | false | ```\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n product = []\n for i in range(len(searchWord)):\n p = []\n for prod in products:\n if prod.startswith(searchWord[:i+1]):\n p.append(prod)\n p = sorted(p)[:3]\n product.append(p)\n return product\n``` | 4 | 0 | ['Python', 'Python3'] | 4 |
search-suggestions-system | Simple and easily understandable solution | simple-and-easily-understandable-solutio-hdj7 | First sort the words array that was which will actually sort the words in lexographical order.\nNow find out the words that have 1st letter as common with that | Sathish_McCall | NORMAL | 2022-06-19T06:19:13.688816+00:00 | 2022-06-19T06:25:35.818047+00:00 | 142 | false | First sort the words array that was which will actually sort the words in lexographical order.\nNow find out the words that have 1st letter as common with that of search word and append them to dp array.\nNext we will search for the second letter from the dp array of 1st letter ,\nAnd we will continue till the end .\nAt the end we are left with the dp array which has all the words, but in question it is mentioned that we should only have 3 words in lexographical order, as we have already sorted the words array we can directly take top three of each array.\n***\'\'\'\nclass Solution:\n def suggestedProducts(self, p: List[str], s: str) -> List[List[str]]:\n dp=[[] for in range(len(s))]\n def fun(i):\n if i==len(s):\n return\n for j in dp[i-1]:\n if i<len(j):\n if j[i]==s[i]:\n dp[i].append(j)\n fun(i+1)\n p.sort()\n for i in range(len(p)):\n if p[i][0]==s[0]:\n dp[0].append(p[i])\n fun(1)\n for i in dp:\n for j in range(len(i)-1,-1,-1):\n if j>2:\n i.pop(j)\n else:\n break\n return dp*\n \n\t\t\t\'\'\'\n | 4 | 0 | [] | 0 |
search-suggestions-system | Python Trie Solution | python-trie-solution-by-shams7-5nwl | \nclass TrieNode:\n def __init__(self,char):\n self.char = char\n self.isWord = False\n self.children = {}\n\nclass Trie:\n def __ini | shams7 | NORMAL | 2022-05-15T15:47:30.673818+00:00 | 2022-05-15T15:47:30.673903+00:00 | 205 | false | ```\nclass TrieNode:\n def __init__(self,char):\n self.char = char\n self.isWord = False\n self.children = {}\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode("")\n \n def insert(self,word):\n node = self.root\n\n for char in word:\n if char in node.children:\n node = node.children[char]\n else:\n node.children[char] = TrieNode(char)\n node = node.children[char]\n node.isWord = True\n \n def dfs(self,node,prefix):\n \n if len(self.output)==3:\n return\n if node.isWord:\n self.output.append(prefix + node.char)\n for child in node.children.values():\n self.dfs(child, prefix + node.char)\n\n def getSuggestion(self,word):\n\n node = self.root\n \n for char in word:\n if char in node.children:\n node = node.children[char]\n else:\n return []\n self.output = []\n self.dfs(node, word[:-1])\n\n return self.output\n\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \n products = sorted(products)\n trie = Trie()\n for product in products:\n trie.insert(product)\n \n \n prefix = ""\n ans = []\n \n for char in searchWord:\n prefix += char\n ans.append(trie.getSuggestion(prefix))\n return ans\n\n```\n | 4 | 0 | ['Depth-First Search', 'Trie', 'Python'] | 1 |
search-suggestions-system | [Python] Trie solution explained | python-trie-solution-explained-by-buccat-rbuy | \nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.end = False\n self.suggestions = list()\n\nclass Solution:\n def | buccatini | NORMAL | 2022-04-14T02:15:57.125411+00:00 | 2022-04-14T02:15:57.125437+00:00 | 386 | false | ```\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.end = False\n self.suggestions = list()\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n root = TrieNode()\n \n # sort the input lexicographically\n # before inserting them into the trie\n products.sort()\n \n # now, the usual trie insertion\n # pattern but for every word given to us\n for product in products:\n cur = root\n for letter in product:\n if letter not in cur.children:\n cur.children[letter] = TrieNode()\n cur = cur.children[letter]\n \n # once we\'ve moved to the first letter\n # of the current word, add the current\n # word to it\'s suggestion list (at most 3)\n # and this list will be sorted since we\'ve\n # done the sorting beforehand\n # now, for every letter for every word in the trie\n # it\'ll have an additional list with the 3 most\n # close suggestions\n if len(cur.suggestions) < 3:\n cur.suggestions.append(product)\n \n cur.end = True\n \n # init the result object, the judge\n # needs this pattern if there are\n # no valid answers\n res = [[]] * len(searchWord)\n \n cur = root\n \n # iterate over all the letters\n # in the given searchWord and\n # gather the suggestions\n for i in range(len(searchWord)):\n if searchWord[i] not in cur.children:\n break\n \n # we\'re moving to the node before\n # getting the suggestions because\n # in the first iteration, this will\n # be the root node (we followed a similar\n # pattern while populating the trie too)\n cur = cur.children[searchWord[i]]\n res[i] = cur.suggestions\n \n return res\n``` | 4 | 0 | ['Trie', 'Python', 'Python3'] | 2 |
search-suggestions-system | [Python] Simple approach using Brute Force (84 ms, faster than 93.2%) | python-simple-approach-using-brute-force-x0mh | class Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \n res = []\n\t\t# Initializing empty | amanc1997 | NORMAL | 2022-03-07T09:19:14.618420+00:00 | 2022-03-07T09:19:14.618461+00:00 | 268 | false | class Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \n res = []\n\t\t# Initializing empty string temp\n temp = \'\'\n \n\t\t# Sorting the list \n products.sort()\n \n\t\t# Looping through searchWord\n for word in searchWord:\n\t\t\t# Adding each character of searchWord to temp every iteration\n temp += word\n\t\t\t# Initialzing another empty list to keep the matching products\n res_inner = []\n\t\t\t# Looping through the products\n for j in range(len(products)):\n\t\t\t\t# Comparing the product upto the same length as temp instead of finding it in the entire product string\n if (products[j][:len(temp)] == temp):\n\t\t\t\t\t# Appending the found product to the inner list\n res_inner.append(products[j])\n \n\t\t\t# Only considering lexicographically top 3 elements \n res.append(res_inner[:3])\n\t\t\t# Updating the products list to inner list to reduce the search space\n products = res_inner\n \n return res\n\t\t\n\t\t# Kindly upvote if you liked the solution. | 4 | 0 | ['Python', 'Python3'] | 0 |
search-suggestions-system | Java | Trie | OOP | java-trie-oop-by-arrnavvv-f7sa | \n\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n Trie trie = new Trie();\n Arrays.s | arrnavvv | NORMAL | 2022-02-23T15:02:05.020943+00:00 | 2022-02-23T15:02:05.020971+00:00 | 295 | false | \n```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n Trie trie = new Trie();\n Arrays.sort(products);\n for(String p : products){\n trie.insert(p);\n }\n \n List<List<String>> res = trie.getResult(searchWord);\n return res;\n }\n}\n\nclass Trie{\n Node root;\n \n public Trie(){\n root = new Node();\n }\n \n void insert(String word){\n Node curr = root;\n for(int i=0;i<word.length();i++){\n char c = word.charAt(i);\n if(!curr.containsKey(c)){\n curr.put(c, new Node());\n }\n curr = curr.get(c);\n curr.addToList(word);\n }\n }\n \n List<List<String>> getResult(String searchWord){\n Node curr = root;\n List<List<String>> res = new ArrayList<>();\n for(int i=0;i<searchWord.length();i++){\n char c= searchWord.charAt(i);\n List<String> temp = new ArrayList<>();\n if(curr!=null) curr = curr.get(c);\n \n for(int j=0;j<3 && curr!=null && j<curr.getList().size();j++){\n temp.add(curr.getList().get(j));\n }\n res.add(new ArrayList<>(temp));\n }\n return res;\n }\n \n}\n\nclass Node{\n Node[] links;\n List<String> list;\n \n public Node(){\n links = new Node[26];\n list = new ArrayList<>();\n }\n \n boolean containsKey(char c){\n return links[c-\'a\']!=null;\n }\n \n Node get(char c){\n return links[c-\'a\'];\n }\n \n void put(char c, Node node){\n links[c-\'a\'] = node;\n }\n \n void addToList(String s){\n list.add(s);\n }\n \n List<String> getList(){\n return list;\n }\n}\n``` | 4 | 0 | ['Trie', 'Java'] | 1 |
search-suggestions-system | [C++] Binary search & trie | c-binary-search-trie-by-codedayday-f936 | Approach 1: Binary Search [1]\nTime Complexity: O(NlogN) + O(MlogN), where N=|products|, M= |searchWord|\nSpace: O(1)\n\nclass Solution {\npublic:\n vector<v | codedayday | NORMAL | 2021-05-31T17:15:57.039571+00:00 | 2021-05-31T17:38:15.653533+00:00 | 256 | false | Approach 1: Binary Search [1]\nTime Complexity: O(NlogN) + O(MlogN), where N=|products|, M= |searchWord|\nSpace: O(1)\n```\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n vector<vector<string>> ans;\n sort(products.begin(), products.end());\n string key;\n for(auto c: searchWord){\n key += c;\n auto l=lower_bound(products.begin(), products.end(), key);\n auto r=upper_bound(products.begin(), products.end(), key+=\'~\');\n key.pop_back();\n if(l == r) break;\n ans.emplace_back(l, min(l+3, r)); \n }\n while(ans.size() != searchWord.size()) ans.push_back({});\n return ans; \n }\n};\n```\n\nApproach 2:trie [1]\nInitialization: Sum(len(products[i]))\nQuery: O(len(searchWord))\n```\nstruct Trie {\n Trie(): nodes(26) {}\n ~Trie() { \n for (auto* node : nodes)\n delete node;\n }\n vector<Trie*> nodes;\n vector<const string*> words; \n \n static void addWord(Trie* root, const string& word) { \n for (char c : word) { \n if (root->nodes[c - \'a\'] == nullptr) root->nodes[c - \'a\'] = new Trie();\n root = root->nodes[c - \'a\'];\n if (root->words.size() < 3)\n root->words.push_back(&word);\n }\n }\n \n static vector<vector<string>> getWords(Trie* root, const string& prefix) {\n vector<vector<string>> ans(prefix.size());\n for (int i = 0; i < prefix.size(); ++i) {\n char c = prefix[i];\n root = root->nodes[c - \'a\'];\n if (root == nullptr) break;\n for (auto* word : root->words)\n ans[i].push_back(*word);\n }\n return ans;\n }\n};\n \nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n std::sort(begin(products), end(products));\n Trie root;\n for (const auto& product : products)\n Trie::addWord(&root, product);\n return Trie::getWords(&root, searchWord);\n }\n};\n```\n\nReference:\n[1] https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1268-search-suggestions-system/ | 4 | 0 | ['Trie', 'C', 'Binary Tree'] | 2 |
search-suggestions-system | C++ 2 approaches (Binary Search , Trie) Easy to undersrand code | c-2-approaches-binary-search-trie-easy-t-0txz | Github Link : https://github.com/MAZHARMIK/Interview_DS_Algo/blob/master/Design/Search_Suggestions_System.cpp\n\n//Approach - 1 (First solution that comes in ou | mazhar_mik | NORMAL | 2021-05-31T15:58:13.730244+00:00 | 2021-05-31T15:58:13.730296+00:00 | 71 | false | Github Link : https://github.com/MAZHARMIK/Interview_DS_Algo/blob/master/Design/Search_Suggestions_System.cpp\n```\n//Approach - 1 (First solution that comes in our mind : Using TRIE Data Structure)\nclass Solution {\npublic:\n struct trieNode {\n char ch;\n bool end;\n trieNode* children[26] = {NULL};\n };\n \n trieNode* getNode(char ch) {\n trieNode* temp = new trieNode();\n temp->end = false;\n temp->ch = ch;\n return temp;\n }\n \n void insert(trieNode* root, string key) {\n trieNode* pCrawl = root;\n \n for(char &ch : key) {\n int idx = ch-\'a\';\n \n if(pCrawl->children[idx] == NULL) {\n pCrawl->children[idx] = getNode(ch);\n }\n \n pCrawl = pCrawl->children[idx];\n }\n \n pCrawl->end = true;\n }\n \n void getWord(trieNode* pCrawl, string temp, vector<string>& result) {\n if(result.size() == 3)\n return;\n \n if(pCrawl->end) {\n result.push_back(temp);\n }\n \n for(char ch = \'a\'; ch<=\'z\'; ch++) {\n trieNode* nextNode = pCrawl->children[ch-\'a\'];\n if(nextNode) {\n temp.push_back(ch);\n getWord(nextNode, temp, result);\n temp.pop_back();\n }\n }\n \n }\n \n vector<string> search(trieNode* root, string key) {\n trieNode* pCrawl = root;\n vector<string> result;\n for(char &ch : key) {\n int idx = ch-\'a\';\n if(!pCrawl->children[idx]) {\n return result;\n }\n pCrawl = pCrawl->children[idx];\n }\n \n getWord(pCrawl, key, result);\n \n return result;\n }\n \n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n trieNode* root = getNode(\'.\');\n for(string &product : products) {\n insert(root, product);\n }\n \n vector<vector<string>> result;\n int n = searchWord.length();\n \n string prefix = "";\n for(int i = 0; i<n; i++) {\n prefix.push_back(searchWord[i]);\n result.push_back(search(root, prefix));\n }\n \n return result;\n }\n};\n```\n\n\n```\n//Approach-2 (Since, contraints are low, you can apply Binary Search (Lower bound))\nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n vector<vector<string>> result;\n int n = products.size();\n sort(begin(products), end(products));\n \n string prefix = "";\n int index = 0;\n for(char &ch : searchWord) {\n prefix.push_back(ch);\n \n int start = lower_bound(products.begin() + index, end(products), prefix) - begin(products);\n /*\n NOTE : lower bound returns element which is equal to or greater than the\n search key(prefix here)\n */\n \n result.push_back({});\n \n for(int i = start; i<min(start+3, n); i++) {\n if(products[i].find(prefix) < n) {\n result.back().push_back(products[i]);\n }\n }\n \n index = start;\n }\n \n return result;\n }\n};\n\n``` | 4 | 0 | [] | 0 |
search-suggestions-system | Search Suggestion System | Python | Brute Force | search-suggestion-system-python-brute-fo-fidc | Sort the products array to get lexicographically smallest words and then iterate over products till length of target and check for at most three matching words | sethhritik | NORMAL | 2021-05-31T12:12:57.364679+00:00 | 2021-05-31T12:12:57.364721+00:00 | 240 | false | Sort the products array to get *lexicographically smallest* words and then iterate over products till length of target and check for **at most** three matching words in products with **prefix[0:i+1]**.\n\n```\ndef suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n ans=[]\n n=len(searchWord)\n l=sorted(products)\n for i in range(n):\n pre = searchWord[:i+1]\n t = []\n c=0\n for j in l:\n if j[:i+1]==pre:\n t.append("".join(j))\n c+=1\n if c==3:\n break\n ans.append(t)\n return ans\n``` | 4 | 0 | ['Sliding Window', 'Python', 'Python3'] | 0 |
search-suggestions-system | Python 7-line solution | python-7-line-solution-by-julescui-0oi9 | \nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n result = []\n products.sort()\n | JulesCui | NORMAL | 2021-01-13T22:19:36.165499+00:00 | 2021-01-13T22:19:36.165538+00:00 | 362 | false | ```\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n result = []\n products.sort()\n for x in range(len(searchWord)):\n word = searchWord[:x+1]\n products = [item for item in products if item.startswith(word)]\n result.append(products[:3])\n return result\n``` | 4 | 0 | ['Python', 'Python3'] | 1 |
search-suggestions-system | Java concise Trie | java-concise-trie-by-hjscoder-m8db | Code: \n\n\nclass Solution {\n class Node {\n char val;\n HashMap<Character, Node> children;\n List<String> suggestion;\n publi | hjscoder | NORMAL | 2020-09-04T19:51:01.202133+00:00 | 2020-09-04T19:51:01.202173+00:00 | 225 | false | <h4> Code: </h4>\n\n```\nclass Solution {\n class Node {\n char val;\n HashMap<Character, Node> children;\n List<String> suggestion;\n public Node(char val) {\n this.val = val;\n this.children = new HashMap<Character, Node>();\n this.suggestion = new ArrayList<>();\n }\n }\n \n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n Arrays.sort(products); \n Node root = new Node(\' \');\n for (String product : products) {\n add(root, product);\n }\n List<List<String>> ans = new ArrayList<>();\n for (char c : searchWord.toCharArray()) { \n if (root != null) root = root.children.get(c);\n ans.add(root == null ? new ArrayList<>() : root.suggestion);\n }\n return ans;\n }\n\n public void add(Node root, String product) {\n Node node = root;\n for (char c : product.toCharArray()) { \n if (node.children.get(c) == null) node.children.put(c, new Node(c));\n node = node.children.get(c);\n if (node.suggestion.size() < 3) node.suggestion.add(product);\n }\n }\n}\n```\n | 4 | 0 | [] | 0 |
search-suggestions-system | JAVA beats 97.45% time(7ms) 100% memory... No Trie, No Binary Search | java-beats-9745-time7ms-100-memory-no-tr-m9e0 | \nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new ArrayList<>(); | vision2yrs | NORMAL | 2020-05-14T08:18:00.300667+00:00 | 2020-05-14T08:19:59.228533+00:00 | 556 | false | ```\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> ans = new ArrayList<>();\n for (int i = 0; i < searchWord.length(); ++i) {\n ans.add(new ArrayList<>());\n }\n List<String> temp = null;\n Arrays.sort(products);\n for (int i = 0; i < products.length; ++i) {\n int commonPrefix = match(products[i], searchWord);\n for (int j = commonPrefix - 1; j >= 0; --j) {\n temp = ans.get(j);\n if (temp.size() == 3) {\n break;\n }\n temp.add(products[i]);\n }\n }\n return ans;\n }\n\n private int match(String one, String two) {\n int i = 0;\n for (i = 0; i < one.length() && i < two.length(); ++i) {\n if (one.charAt(i) != two.charAt(i))\n return i;\n }\n return i;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
search-suggestions-system | Swift Trie | swift-trie-by-charlychuanli-wdjq | ```\nfunc suggestedProducts( products: [String], _ searchWord: String) -> [[String]] {\n var root = Trie()\n for product in products {\n | charlychuanli | NORMAL | 2020-05-09T23:35:27.761147+00:00 | 2020-05-09T23:35:27.761199+00:00 | 290 | false | ```\nfunc suggestedProducts(_ products: [String], _ searchWord: String) -> [[String]] {\n var root = Trie()\n for product in products {\n var cur = root\n cur.build(cur, product)\n }\n var res = [[String]]()\n \n for char in searchWord {\n \n if let node = root.child[char] {\n res.append(node.words)\n root = node\n } else {\n res.append([])\n root.child.removeAll()\n }\n \n }\n \n res = res.map({ $0.sorted(by: <)} )\n return res.map({ Array($0.prefix(3))})\n }\n}\n\nclass Trie {\n var child = [Character: Trie]()\n var words = [String]()\n \n func build(_ root: Trie, _ word: String) {\n var root = root\n for char in word {\n if root.child[char] == nil {\n var newNode = Trie()\n root.child[char] = newNode\n newNode.words.append(word)\n root = newNode\n } else {\n var node = root.child[char]!\n node.words.append(word)\n root = node\n }\n }\n }\n} | 4 | 0 | [] | 3 |
search-suggestions-system | SIMPLE BINARY SEARCH C++ SOLUTION | simple-binary-search-c-solution-by-jeffr-5a39 | 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 | Jeffrin2005 | NORMAL | 2024-08-10T04:37:09.912003+00:00 | 2024-08-10T04:37:09.912026+00:00 | 799 | 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```\n#include <bits/stdc++.h>\n#define ll long long \nclass Solution {\npublic:\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n sort(products.begin(), products.end()); \n vector<vector<string>>result;\n string currentPrefix = "";\n for(auto&c : searchWord){\n currentPrefix+=c; // Build the prefix incrementally\n vector<string> suggestions;\n // Use lower_bound to find the first product that is not less than the current prefix\n auto it = lower_bound(products.begin(), products.end(), currentPrefix);\n // Collect up to three valid suggestions\n int i = 0;\n while(i < 3 && it != products.end() && it->substr(0, currentPrefix.size()) == currentPrefix){\n suggestions.push_back(*it);\n ++i;\n ++it;\n }\n result.push_back(suggestions);\n }\n \n return result;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
search-suggestions-system | Search Suggestions System C++ Solution | search-suggestions-system-c-solution-by-cjdny | Code\n\nstruct Node{\n Node* links[26];\n bool flag = false;\n vector<string>words;\n bool containsKey(char ch){\n return links[ch-\'a\']!=NU | rissabh361 | NORMAL | 2023-09-12T18:00:35.859400+00:00 | 2023-09-12T18:00:35.859424+00:00 | 1,135 | false | # Code\n```\nstruct Node{\n Node* links[26];\n bool flag = false;\n vector<string>words;\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};\nclass Solution {\npublic:\n void insert(Node* trie,string word,stack<Node*>&st){\n st.push(trie);\n for(int i=0;i<word.length();i++){\n if(!trie->containsKey(word[i])){\n trie->put(word[i],new Node());\n }\n trie = trie->get(word[i]);\n st.push(trie);\n }\n trie->setEnd();\n }\n vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n vector<vector<string>>ans(searchWord.length());\n sort(products.begin(),products.end());\n Node* trie = new Node();\n for(auto word:products){\n stack<Node*>st;\n insert(trie,word,st);\n while(!st.empty()){\n Node* temp = st.top();\n st.pop();\n if(temp->words.size()<3)temp->words.push_back(word);\n }\n }\n for(int i=0;i<searchWord.length();i++){\n if(!trie->containsKey(searchWord[i])){\n return ans;\n }\n trie = trie->get(searchWord[i]);\n ans[i]=trie->words;\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Array', 'String', 'Binary Search', 'Trie', 'Sorting', 'Heap (Priority Queue)', 'C++'] | 0 |
search-suggestions-system | [Java] 2 solutions: Sorting (100%) / using Trie and BackTracking (65%) | java-2-solutions-sorting-100-using-trie-et5x3 | 65% runtime, but better if we had to reuse the search function (in a design scenario).\n\njava\nclass Solution {\n public List<List<String>> suggestedProduct | YTchouar | NORMAL | 2023-05-31T18:59:17.321306+00:00 | 2023-05-31T21:12:33.842681+00:00 | 540 | false | 65% runtime, but better if we had to reuse the search function (in a design scenario).\n\n```java\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n final TrieNode root = this.buildTree(products);\n final List<List<String>> result = new ArrayList<>();\n\n for(int i = 0; i < searchWord.length(); ++i)\n result.add(new ArrayList<>());\n\n this.search(root, result, 0, new StringBuilder(), searchWord, false);\n\n for(int i = result.size() - 2; i >= 0; --i) {\n result.get(i).addAll(result.get(i + 1));\n Collections.sort(result.get(i));\n result.set(i, result.get(i).subList(0, Math.min(3, result.get(i).size())));\n }\n\n return result;\n }\n\n private void search(final TrieNode node, final List<List<String>> result, int height, final StringBuilder sb, String word, boolean expandSearch) {\n if(height == word.length())\n height--;\n\n if(expandSearch) {\n for(int i = 0; i < 26; ++i) {\n if(result.get(height).size() > 2)\n return;\n\n final TrieNode curr = node.children(i);\n\n if(curr != null) {\n sb.append((char) (i + \'a\'));\n\n if(curr.isWord())\n result.get(height).add(sb.toString());\n\n search(curr, result, height, sb, word, expandSearch);\n sb.deleteCharAt(sb.length() - 1);\n }\n }\n } else {\n TrieNode curr = node.children(word.charAt(height) - \'a\');\n\n if(curr != null) {\n sb.append(word.charAt(height));\n\n if(curr.isWord())\n result.get(height).add(sb.toString());\n\n search(curr, result, height + 1, sb, word, height + 1 >= word.length());\n sb.deleteCharAt(sb.length() - 1);\n }\n\n if(height >= 1) {\n for(int i = 0; i < 26; ++i) {\n if(result.get(height - 1).size() > 3)\n return;\n\n if(i == word.charAt(height) - \'a\')\n continue;\n\n curr = node.children(i);\n\n if(curr != null) {\n sb.append((char) (i + \'a\'));\n\n if(curr.isWord())\n result.get(height - 1).add(sb.toString());\n\n search(curr, result, height - 1, sb, word, true);\n sb.deleteCharAt(sb.length() - 1);\n }\n }\n }\n }\n }\n\n\n private TrieNode buildTree(final String[] products) {\n final TrieNode root = new TrieNode();\n\n for(String product : products) {\n TrieNode node = root;\n\n for(int i = 0; i < product.length(); ++i) {\n final int index = product.charAt(i) - \'a\';\n\n if(node.children(index) == null)\n node.children(index, new TrieNode());\n node = node.children(index);\n }\n\n node.isWord(true);\n }\n\n return root;\n }\n\n private final class TrieNode {\n private final TrieNode[] children;\n private boolean isWord;\n\n public TrieNode() {\n this.children = new TrieNode[26];\n this.isWord = false;\n }\n\n public TrieNode children(final int index) {\n return this.children[index];\n }\n\n public void children(final int index, final TrieNode node) {\n this.children[index] = node;\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}\n```\n\n100% runtime solution with sorting.\n\n```java\nclass Solution {\n public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n List<List<String>> result = new ArrayList<>();\n\n Arrays.sort(products);\n\n for(int i = 0; i < searchWord.length(); ++i)\n result.add(new ArrayList<>());\n\n int count = 0;\n\n for(int i = 0; i < products.length; ++i) {\n if(count == searchWord.length() * 3)\n break;\n\n int len = Math.min(searchWord.length(), products[i].length());\n\n for(int j = 0; j < len; ++j) {\n if(products[i].charAt(j) == searchWord.charAt(j)) {\n List<String> list = result.get(j);\n\n if(list.size() < 3) {\n list.add(products[i]);\n count++;\n }\n } else {\n break;\n }\n }\n }\n \n return result;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | c++ 2 pointers with detail proof and explanation | c-2-pointers-with-detail-proof-and-expla-h3sy | In this post I \'m not trying to give the most efficient algorithm or the simplest code. I just try to explain the essence of the problem.\n\nA palindrome is an | hl1008 | NORMAL | 2022-03-13T20:08:46.843303+00:00 | 2022-05-21T12:19:30.901521+00:00 | 16,438 | false | In this post I \'m not trying to give the most efficient algorithm or the simplest code. I just try to explain the essence of the problem.\n\nA palindrome is an axial symmetry string. Every position holds the same letter with its position symmetry. \n\n<img src="https://assets.leetcode.com/users/images/05b7eb94-bdf5-409a-b96a-6daf13cdbefb_1647201205.0560412.png" alt="drawing" width="700"/>\n\n\n\nThe most common idea that we can come up with is using two pointers for the left end and right end. If the current two letters are the same, we advance the pointer. If not, we search for the nearest letter that will make them same and swap it. Look at the following example. \n1. The current two letters \'a\' and \'d\' are different. \n2. We need to exchange one of them to be the same with the other. Notice here, you may keep either one of them. Though the final string may be different, the count of moves we spend are equal(you\'ll see that later). Here let\'s keep the right end letter \'d\' and search for the nearest \'d\' from the left end.\n\n<img src="https://assets.leetcode.com/users/images/7b842f9f-2350-4517-aebf-ee9483ee151b_1647201247.1059253.png" alt="drawing" width="700"/>\n\n3. After we find the nearest \'d\', we need to swap it to the 0-position.\n\n<img src="https://assets.leetcode.com/users/images/3b3270d3-5637-4232-9cc8-c4f5fae42ae1_1647201266.464941.png" alt="drawing" width="700"/>\n\n4. We advance the two pointers and repeat the same steps until the two pointers meet.\n\n<img src="https://assets.leetcode.com/users/images/d1ef03b5-8b45-4a93-a157-7316f3886cb4_1647201281.6635847.png" alt="drawing" width="700"/>\n\n\nI believe the aforementioned method is easy to understand. However, the difficulty is how we can know the method leads to the minimum moves. Can we convert the string to an arbitrary palindrome with minimal moves? If not, what kind of string we can convert to with minimal moves?\n\n**The key point is relative order between the letters.**\n\nSince the palindrome is axial symmetry, the same letter pair in the left part and right part must have the opposite relative order. So if two letter pairs have the same relative order, you can\'t avoid swapping them. In the meantime, if two letter pairs already have the opposite relative order, you should avoid swapping them, or you\'ll introduce redundant moves and lead to non-optimal solution.\n\nLet\'s look at the example now. All the letters in the left part and right part have the same order. \n\n<img src="https://assets.leetcode.com/users/images/b0cb65ed-38a6-4b55-aa58-d7ebfbc76006_1647201297.2784958.png" alt="drawing" width="700"/>\n\nSo you need to swap letters to make all the letter pairs in left and right opposite. You don\'t have to start from the end, and you can convert either left part or right part. Though this can lead to different palindrome, they all cost the same moves. See the below moves which randomly select the letter pair to swap. After 6 moves, it ends with a different palindrome compared to the former solution.\n\n<img src="https://assets.leetcode.com/users/images/e94bd00b-3354-4107-a134-efe9110d528d_1647201351.8659885.png" alt="drawing" width="300"/>\n\nWhen we say "randomly" here, it means the order of the letter pair we swap. In fact, you can see that all the letter pairs we swap are exactly the combination of the 4 letters \'abcd\'. That\'s why we need 6 moves. We swap every letter pair because in this example, all the letter pair from left and right have the same order. So they all need to be swapped once each. \nLet\'s look at another example. \n\n<img src="https://assets.leetcode.com/users/images/0a16b279-dff9-41fb-982a-f46696a80c1e_1647201374.874811.png" alt="drawing" width="700"/>\n\nIn this example, let\'s compare the letter pairs relative order in left and right side.\n(a, b) -- (b, a) -- opposite\n(a, c) -- (c, a) -- opposite\n(a, d) -- (a, d) -- same\n(b, c) -- (b, c) -- same\n(b, d) -- (b, d) -- same\n(c, d) -- (c, d) -- same\nSo, we need to swap 4 letter pairs at least.\n\nWe see that (a, b) and (a, c) pair already have the opposite order in the left and right side. So they don\'t need to be swapped again. But for all the other 4 letter pairs, they still need to be swapped. During your solution you should avoid swapping the letter pair that are already in their right order. \nSee below, you should not try to swap (c,d) first, which will cause (c, a) be swapped. The same with (b, d).\n\n<img src="https://assets.leetcode.com/users/images/770e6660-c9f2-447b-be4b-44127be57754_1647201397.2791355.png" alt="drawing" width="700"/>\n\n\nSo you can swap (a,d) or (b,c) either you like.\n\n\n<img src="https://assets.leetcode.com/users/images/2545dcef-6b66-4996-bed8-f6c2cb58a7bc_1647201429.7843585.png" alt="drawing" width="500"/>\n\nAfter 4 moves, we get to the end.\n\nTill now, let\'s answer the question posed earlier. What kind of palindrome can we convert to with minimal moves? The answer should be the palindromes that keep the letter pair order which have already met the conditions. \nIn the above example "abcdbcad", palindromes like "cabddbac", "bacddcab" are definitely impossible with minimal moves to convert to. Because they require to swap (a,c), (a, b) which are already in good state.\n\nLet\'s try a little more tricky example. The letters are not located on their target side. So what we should keep in mind is just do the necessary swap. \n\n<img src="https://assets.leetcode.com/users/images/43b6273c-3ff4-458d-a93b-f51f15c17eec_1647201462.2549217.png" alt="drawing" width="700"/>\n\nFirst, we need to know which letter belongs to which side. We should choose the closest letters to each side in order to reduce the moves. Green ones belong to the left side while blue ones belong to the right side.\n\n<img src="https://assets.leetcode.com/users/images/9cdeae3b-e49d-44f7-97b8-488b3c4af38e_1647201475.2718742.png" alt="drawing" width="700"/>\n\nNow, besides keeping the relative orders, we still need to think about the side. We can not avoid the moves that swap all the blue ones to the right of the green ones.\n\n<img src="https://assets.leetcode.com/users/images/97d0aa9e-c8a5-4748-8112-f1f91df983e8_1647201505.9667459.png" alt="drawing" width="700"/>\n\n\nFinally, let\'s see why the two pointers algorithm work well. See below, if you keep right end \'d\' still, you know that all the other letters are to its left. So when you find and swap the nearest \'d\' to left end , you are sure that every single swap you make isn\'t unnecessary, because \'d\' should be in front of all of them. \n\n<img src="https://assets.leetcode.com/users/images/52baf247-4204-45c6-b445-04b31619e35b_1647201520.1659758.png" alt="drawing" width="700"/>\n\n\nAfter the whole idea is clear, let\'s talk a little bit about a special case we need to notice. When the string length is odd, there must be a letter that has no partner. See the following example, the \'z\' has no counterpart. So when we try to search \'z\' from the left end, we will end up meeting the right end pointer q. In that case, we know \'z\' should be the centerpoint of the result. \n\n<img src="https://assets.leetcode.com/users/images/cd584ade-5e37-4873-b1bc-c8edba1057db_1647201537.4622815.png" alt="drawing" width="700"/>\n\nYou can record the position of \'z\' and advance the q pointer. At the end of the whole process, you can swap \'z\' to the centerpoint. Notice here, you should avoid trying to swap the \'z\' to the center before the whole process ends. That is because at this time you can\'t guarantee all the swap you do is necessary. See the example below. The green \'d\' is swapped to the right side of \'z\' which is an unnecessary cost, because it should be on the left size at the end. However, when you do this after the whole process ends, you won\'t have this problem.\n<img src="https://assets.leetcode.com/users/images/96fe39f1-06bd-4a38-8344-0e643a562187_1653135480.8935752.png" alt="drawing" width="700"/>\n\n```\nindrome(string s) {\n \n int l = 0;\n int r = s.length() - 1;\n\n int count = 0;\n int center_i = -1;\n \n while (l < r) {\n if (s[l] == s[r]) {\n l++;\n r--;\n continue;\n }\n\n int k = l + 1;\n for (; k < r; k++) {\n if (s[k] == s[r]) {\n break;\n }\n }\n\n if (k == r) {\n center_i = r;\n r--;\n continue;\n }\n\n for (int j = k; j > l; j--) {\n swapChar(j, j - 1);\n count++;\n }\n \n l++;\n r--;\n }\n \n if (center_i != -1) {\n count += (center_i - s.size() / 2);\n } \n \n return count;\n }\n};\n``` | 306 | 0 | ['C', 'C++'] | 21 |
minimum-number-of-moves-to-make-palindrome | [C++/Python] Short Greedy Solution | cpython-short-greedy-solution-by-lee215-1yx1 | Explanation\nConsidering the first and the last char in final palindrome.\nIf they are neither the first nor the last char in the initial string,\nyou must wast | lee215 | NORMAL | 2022-03-05T16:14:38.594921+00:00 | 2022-03-05T16:53:58.514556+00:00 | 18,025 | false | # **Explanation**\nConsidering the first and the last char in final palindrome.\nIf they are neither the first nor the last char in the initial string,\nyou must waste some steps:\nAssume start with "...a....a.."\n".a.......a." can be ealier completed thand "a.........a".\n\nThen compare the situation "a....b..a...b"\nIt takes same number of steps to "ab.........ba" and "ba.........ab".\nSo we can actually greedy move the characters to match string prefix.\n\nOther reference: https://www.codechef.com/problems/ENCD12\n\n# **Complexity**\nTime `O(n^2)`, can be improved to `O(nlogn)` by segment tree\nSpace `O(n)`\n\n**C++**\n```cpp\n int minMovesToMakePalindrome(string s) {\n int res = 0;\n while (s.size()) { \n int i = s.find(s.back());\n if (i == s.size() - 1)\n res += i / 2;\n else\n res += i, s.erase(i, 1);\n s.pop_back();\n }\n return res; \n }\n```\n**Python**\n```py\n def minMovesToMakePalindrome(self, s):\n s = list(s)\n res = 0\n while s:\n i = s.index(s[-1])\n if i == len(s) - 1:\n res += i / 2\n else:\n res += i\n s.pop(i)\n s.pop()\n return res\n```\n | 186 | 5 | [] | 26 |
minimum-number-of-moves-to-make-palindrome | [Java, C++] 2 pointers. Step-by-step dry-run for easy explanation | java-c-2-pointers-step-by-step-dry-run-f-bahk | Below is the dry-run and detailed steps using example string "aletelt". Do "Upvote" if it helps :) \n\t\n#### \tComplexity\n\tTime: O(n^2), Space: O(n)\n\t\n# | karankhara | NORMAL | 2022-03-05T22:49:16.888405+00:00 | 2022-03-14T22:31:02.068826+00:00 | 9,483 | false | Below is the dry-run and detailed steps using example string "aletelt". Do "**Upvote**" if it helps :) \n\t\n#### \tComplexity\n\tTime: O(n^2), Space: O(n)\n\t\n#### \tApproach:\n\tIntially, steps = 0.\n\t* \tWe will use 2 index pointers initially - "l" as Left and "r" as right. \n\t* \t\'l\' will move to right and \'r\' will move to left in each iteration. ( l --> <-- r ) \n\t* \tEach time, we want to check whether characters at "l" & "r" are equal. \n\t\t* \tIf yes, then we dont need to do anything as both characters on left & right boundry already are palindrome. Hence, we do l++ & r--.\n\t\t* \tElse, we assign a index pointer "k" at same index as "r". It\'s purpose is to find kth index of character matching with (equal to)\n\t\t\tcharacter at lth index. So, keep moving this pointer towards left until we find the character. We did this in code using\n\t\t method findKthIndexMatchingwithLthIndex().\n\t\t\t* \tIf character not found, k index will reach at index of l. (k==l).\n\t\t\t* \tElse, if found, now we want to bring this character to the index of "r". Hence keep swapping while(k < r). \n\t* \tRepeat above steps. \t\n \n#### \t\tExample & Dry-run\n "a l e t e l t"\n l r // strArr[l] != strArr[r]. initiate index k = r\n k // loop through k using method findKthIndexMatchingwithLthIndex(), until strArr[l] == strArr[k]\n \n "a l e t e l t"\n l r\n k // k reached to index l but did not find any index of k which is equal to strArr[l]\n // So, now swap strArr[l] & strArr[l+1] => now steps = 1\n \n "l a e t e l t" \n l r // strArr[l] != strArr[r]. initiate index k = r\n k // loop through k using method findKthIndexMatchingwithLthIndex(), until strArr[l] == strArr[k]\n \n "l a e t e l t"\n l r\n k // reached k, where strArr[l] == strArr[k] \n // Here k != l, so using while loop, keep swapping element at k and k+1, until k < r. \n\t\t\t\t\t\t\t\t\t\t\t\t\t// Here "steps" will be updated to 2 i.e steps now = 2\n \n "l a e t e t l" \n l r\n k // now do l++ and r--\n \n "l a e t e t l" \n l r\n k \n \n Similarly, keep following above steps or below code, below will be rest of the dry run.\n \n "l a e t e t l" // strArr[l] != strArr[r]\n l r\n k\n \n "l a e t e t l" \n l r\n k // k reached to index l but did not find any index of k which is equal to str[l]\n // So, now swap strArr[l] & strArr[l+1] => now steps = 3\n \n "l e a t e t l" // strArr[l] != strArr[r]\n l r \n k\n \n "l e a t e t l"\n l r \n k // reached k, where strArr[l] == strArr[k] \n // Here k != l, so using while loop, keep swapping element at k and k+1, until k < r. \n\t\t\t\t\t\t\t\t\t\t\t\t\tHere "steps" will be updated to 4 i.e steps now = 4\n \n "l e a t t e l"\n l r \n k\n \n "l e a t t e l" \n l r\n k\n \n "l e a t t e l" \n l r\n k // k reached to index l but did not find any index of k which is equal to str[l]\n // So, now swap strArr[l] & strArr[l+1] => now steps = 5\n \n "l e t a t e l" // We have got palindrome by now\n l r \n k\n\t\t\t\t\t\t\t\n\t\tDo "Upvote" if it helps :) \n\t\t\n\t\t\n### JAVA code:\n\tclass Solution {\n\n\t\tpublic int minMovesToMakePalindrome(String s) {\n\t\t\tint len = s.length();\n\t\t\tchar[] strArr = s.toCharArray(); \n\t\t\tint steps = 0;\n\t\t\tint l = 0, r = len-1; // use two pointers l for left and r for right. \n\n\t\t\twhile(l < r){ \n\t\t\t\tif(strArr[l] == strArr[r]){ // Both characters are equal. so keep going futher.\n\t\t\t\t\tl++; r--;\n\t\t\t\t}else{ // Both characters are not equal. \n\t\t\t\t\tint k = r;\n\t\t\t\t\tk = findKthIndexMatchingwithLthIndex(strArr, l, k); // loop through k, until char at index k = char at index l \n\n\t\t\t\t\tif(k == l){ // we did not find any char at k = char at index l \n\t\t\t\t\t\tswap(strArr, l);\n\t\t\t\t\t\tsteps++; \n\t\t\t\t\t}else{ \n\t\t\t\t\t\twhile(k < r){ \n\t\t\t\t\t\t\tswap(strArr, k);\n\t\t\t\t\t\t\tsteps++;\n\t\t\t\t\t\t\tk++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tl++; r--;\n\t\t\t\t\t} \n\t\t\t\t}// end of else\n\n\t\t\t} // end of while\n\t\t\tSystem.out.println("palindrome: "+String.valueOf(strArr));\n\t\t\treturn steps;\n\n\t\t}\n\n\t\tpublic int findKthIndexMatchingwithLthIndex(char[] strArr, int l, int k){\n\t\t\twhile(k > l){\n\t\t\t\tif(strArr[k] == strArr[l]){ return k; } \n\t\t\t\tk--;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\n\t\tpublic void swap(char[] strArr, int l){\n\t\t\tif(l+1 < strArr.length){\n\t\t\t\tchar tempCh = strArr[l];\n\t\t\t\tstrArr[l] = strArr[l+1];\n\t\t\t\tstrArr[l+1] = tempCh;\n\t\t\t}\n\t\t}\n\t}\n//\n//\n//\n//\n\t\n### \tC++ Code:\n\t\n\tclass Solution {\n\tpublic:\n\t\tint minMovesToMakePalindrome(string s) {\n\t\t\tint len = s.length();\n\t\t\tstring strArr = s; \n\t\t\tint steps = 0;\n\t\t\tint l = 0, r = len-1; // use two pointers l for left and r for right. \n\n\t\t\twhile(l < r){ \n\t\t\t\tif(strArr[l] == strArr[r]){ // Both characters are equal. so keep going futher.\n\t\t\t\t\tl++; r--;\n\t\t\t\t}else{ // Both characters are not equal. \n\t\t\t\t\tint k = r;\n\t\t\t\t\tk = findKthIndexMatchingwithLthIndex(strArr, l, k); // loop through k, until char at index k = char at index l \n\n\t\t\t\t\tif(k == l){ // we did not find any char at k = char at index l \n\t\t\t\t\t\tswap(strArr[l], strArr[l+1]);\n\t\t\t\t\t\tsteps++; \n\t\t\t\t\t}else{ \n\t\t\t\t\t\twhile(k < r){ \n\t\t\t\t\t\t\tswap(strArr[k], strArr[k+1]);\n\t\t\t\t\t\t\tsteps++;\n\t\t\t\t\t\t\tk++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tl++; r--;\n\t\t\t\t\t} \n\t\t\t\t} // end of else\n\n\t\t\t} // end of while\n\t\t\treturn steps;\n\t\t}\n\n\t\tint findKthIndexMatchingwithLthIndex(string strArr, int l, int k){\n\t\t\twhile(k > l){\n\t\t\t\tif(strArr[k] == strArr[l]){ return k; } \n\t\t\t\tk--;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\t};\n\nDo "**Upvote**" if it helps :) \nAny suggestions, question, or more optimized solution is welcomed. | 131 | 3 | ['Greedy', 'C', 'Java'] | 12 |
minimum-number-of-moves-to-make-palindrome | [Python] 2 solutions: O(n^2) and O(n log n), explained | python-2-solutions-on2-and-on-log-n-expl-1e9d | Solution 1\nThe idea is to greedy construct palindrome, symbol by symbol, using two pointers technique. Imagine that we have abc...cdeba. Then for the first two | dbabichev | NORMAL | 2022-03-05T16:01:33.742718+00:00 | 2022-03-05T16:20:50.822946+00:00 | 7,547 | false | #### Solution 1\nThe idea is to greedy construct palindrome, symbol by symbol, using two pointers technique. Imagine that we have `abc...cdeba`. Then for the first two symbols they are already on place. For symbol `c`, we start form the `-3` symbol and look for symbol `c`. When we found it, we do swaps. So, we have `abc...dceba -> abc...decba`. Then we proceed in similar way. \n\n#### Complexity\nIt is `O(n^2)` for time and `O(n)` for space.\n\n#### Code\n```python\nclass Solution:\n def minMovesToMakePalindrome(self, s):\n l, r, s = 0, len(s) - 1, list(s)\n ans = 0\n while l < r:\n if s[l] != s[r]:\n k = r\n while k > l and s[k] != s[l]:\n k -= 1\n if k == l:\n ans += 1\n s[l], s[l + 1] = s[l + 1], s[l]\n else:\n while k < r:\n s[k], s[k + 1] = s[k + 1], s[k]\n k += 1\n ans += 1\n l, r = l + 1, r - 1\n else:\n l, r = l + 1, r - 1\n return ans\n```\n\n#### Solution 2 (advanced)\nThere is also `O(n log n)` solution, using BIT, similar idea to CF1616E. The idea is to create `P` first: are pairs of indexes for each letter. Imagine, that we have `a` on positions `0, 4, 9, 11`, then we create pairs `[0, 11], [4, 9]`. Then we sort these pairs, because we want to proceed them from left to right.\n\nThis solution is inspired by user **TheScrasse** from CodeForces, here is his more detailed explanation:\n\nSince it\'s useless to swap equal characters, you know which pairs of characters will stay on symmetrical positions in the final string, i.e. the i-th leftmost occurrence and the i-th rightmost occurrence of any character `c`. In the string `acabcaaababbc`, for example, you can make these "symmetrical pairs": positions `(1, 10), (2, 13), (3, 8), (4, 12), (6, 7), (9, 11)`. The character in position `5` should go in the center of the final string (i.e. position `7`). The symmetrical pairs have to be nested inside each other, in some order. Given two symmetrical pairs, which of them should be located outside the other one? It turns out that the pair that contains the leftmost element should be located outside. In fact, if you want to reach `xyyx`, the initial configurations with `x` on the left (`xxyy, xyxy, xyyx`) require `2, 1, 0` moves respectively, while reaching `yxxy` requires `2, 1, 2` moves respectively. So you can sort the symmetrical pairs by leftmost element and construct the array a such that `ai` is the final position of `si` in the palindromic string (in this case, `[1, 2, 3, 4, 7, 5, 9, 11, 6, 13, 8, 10, 12]`) and the result is the number of inversions of `a`.\n\n#### Complexity\nIt is `O(n log n)` for time and `O(n)` for space.\n\n#### Code\n```python\nclass BIT:\n def __init__(self, n):\n self.sums = [0] * (n+1)\n \n def update(self, i, delta):\n while i < len(self.sums):\n self.sums[i] += delta\n i += i & (-i)\n \n def query(self, i):\n res = 0\n while i > 0:\n res += self.sums[i]\n i -= i & (-i)\n return res\n\nclass Solution:\n def minMovesToMakePalindrome(self, s):\n n = len(s)\n s = [ord(x) - 95 for x in s]\n ans, bit = 0, BIT(n)\n if sum(x % 2 == 1 for x in Counter(s).values()) > 1: return -1\n\n idx = defaultdict(list)\n for i, c in enumerate(s):\n idx[c].append(i)\n\n B, P = [0] * n, []\n for c, I in idx.items():\n cnt = len(I)\n if cnt % 2:\n B[I[cnt//2]] = n//2 + 1\n for i in range((cnt)//2):\n P += [(I[i], I[~i])]\n\n for i, (l, r) in enumerate(sorted(P)):\n B[l], B[r] = i + 1, n - i\n \n for i, b in enumerate(B):\n ans += i - bit.query(b)\n bit.update(b, 1)\n \n return ans\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please Upvote! | 66 | 7 | ['Two Pointers', 'Greedy'] | 13 |
minimum-number-of-moves-to-make-palindrome | List vs. BIT | list-vs-bit-by-votrubac-ry9g | This question sounds intimidating. Even with 2,000 characters, full search is not practical. Thus, we need to figure out some greedy approach.\n \nIntuition | votrubac | NORMAL | 2022-03-05T16:00:30.231609+00:00 | 2022-03-06T22:21:27.406022+00:00 | 4,912 | false | This question sounds intimidating. Even with 2,000 characters, full search is not practical. Thus, we need to figure out some greedy approach.\n \n**Intuition 1:** It is always cheaper to keep either the left or right character in place, as opposed to moving some other character to the left and right.\n \n **Intuition 2:** It actually does not matter whether we keep the left or right character. Consider this example: \'accabb\'.\n - Keep left: \'acc*a*bb\' -> \'ac*c*bb**a**\' (2 moves) ->\'acbb**c**a\' (2 moves).\n - Keep right: \'acca*b*b\' -> \'**b**accab\' (4 moves).\n \nA simple quadratic solution is accepted (approach 1), and we can improve it to O(n log n) by collecting indexes for each character, and adjusting them using a mutable prefix sum (approach 2).\n\n#### Approach 1: List\nWe will keep the rigth character and move the first matching character from the left.\n \nNote that it is important to use an efficient data structure here - such as a linked list, so we can modify the string in O(1).\n\n**C++**\n```cpp\nint minMovesToMakePalindrome(string s) {\n int res = 0;\n list<char> l(begin(s), end(s));\n while(l.size() > 1) {\n auto it = begin(l);\n int step = 0;\n for (; *it != l.back(); ++it)\n ++step;\n res += step == l.size() - 1 ? step / 2 : step;\n if (it != prev(end(l)))\n l.erase(it);\n l.pop_back();\n }\n return res;\n}\n```\n#### Approach 2: BIT\nWe store indexes for each character in a deque `pos`. Then, for each character on the right, we can find the index of the matching character on the left.\n\nBut wait, we need to adjust the index - by the count of characters we have used before that index. For that, we use BIT to give us a prefix sum in O(log n).\n\n**C++**\n```cpp\nconstexpr int static n = 2000;\nint bt[n + 1] = {};\nint prefix_sum(int i)\n{\n int sum = 0;\n for (i = i + 1; i > 0; i -= i & (-i))\n sum += bt[i];\n return sum;\n}\nvoid add(int i, int val)\n{\n for (i = i + 1; i <= n; i += i & (-i))\n bt[i] += val;\n}\nint minMovesToMakePalindrome(string s) {\n int res = 0, sz = s.size();\n deque<int> pos[26] = {};\n for (int i = 0; i < sz; ++i)\n pos[(s[i] - \'a\')].push_back(i);\n for (int i = sz - 1; i >= 0; --i) {\n int idx = s[i] - \'a\';\n if (!pos[idx].empty()) {\n int p = pos[idx].front() - prefix_sum(pos[idx].front());\n add(pos[idx].front(), 1);\n if (pos[idx].size() > 1)\n pos[idx].pop_front();\n else\n p /= 2;\n res += p;\n pos[idx].pop_back();\n }\n }\n return res;\n}\n``` | 51 | 3 | ['C'] | 12 |
minimum-number-of-moves-to-make-palindrome | Java solution using Greedy | java-solution-using-greedy-by-hss15-g4oy | If a character is at boundry, there is not point in moving it towards center.\nAt any given moment, there can be 2 option for making the boundry palindrome.\nCh | hss15 | NORMAL | 2022-03-05T16:01:07.405812+00:00 | 2022-03-05T16:06:34.691787+00:00 | 4,503 | false | If a character is at boundry, there is not point in moving it towards center.\nAt any given moment, there can be 2 option for making the boundry palindrome.\nChoose the one with minimum value greedily and keep updating the string.\n\n```\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n int count = 0;\n \n while(s.length() > 2) {\n char ch1 = s.charAt(0);\n int len = s.length();\n char ch2 = s.charAt(len - 1);\n \n if (ch1 == ch2) {\n s = s.substring(1, len - 1);\n } else {\n int id1 = s.lastIndexOf(ch1);\n int id2 = s.indexOf(ch2);\n \n int steps1 = len - id1 - 1;\n int steps2 = id2;\n \n StringBuilder sb = new StringBuilder();\n \n if (steps1 > steps2) {\n count += steps2;\n sb.append(s.substring(0, id2));\n sb.append(s.substring(id2 + 1, len - 1));\n } else {\n count += steps1;\n sb.append(s.substring(1, id1));\n sb.append(s.substring(id1 + 1));\n }\n \n s = sb.toString();\n }\n }\n \n return count;\n }\n}\n``` | 47 | 0 | ['Greedy', 'Java'] | 6 |
minimum-number-of-moves-to-make-palindrome | [Python3] 2 pointers solution explained | python3-2-pointers-solution-explained-by-94i1 | \n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n """\n 2 pointers, left and right, such that right = n - left - 1\n | prasanna648 | NORMAL | 2022-03-05T16:02:00.281262+00:00 | 2022-03-05T16:03:33.074818+00:00 | 3,019 | false | ```\n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n """\n 2 pointers, left and right, such that right = n - left - 1\n i.e., they are equidistant from both ends\n \n in a palindromic arrangement of s, s[left] == s[right]\n\n if s[left] and s[right] are not equal:\n 1. from j = right, check whether there is an element equal to s[left]. \n decrement j until an equal element is not found\n 2. similarly, i = left, check whether there is an element equal to s[right].\n increment i until an equal element is not found\n 3. now we need to decide to either move element at left to element at i, or\n element at right to element at j\n 4. calculate the cost for both possibilities, (i - left and right - j)\n 5. choose the minimum and move those elements by adjacent swaps\n \n \n """\n s = list(s)\n n = len(s)\n count = 0\n \n for left in range(n // 2):\n right = n - left - 1\n if s[left] != s[right]:\n i = left\n j = right\n \n while s[left] != s[j]:\n j -= 1\n \n \n while s[right] != s[i]:\n i += 1\n \n \n if right - j < i - left:\n count += right - j\n for x in range(j, right):\n s[x] = s[x+1]\n else:\n count += i - left\n for x in range(i, left, -1):\n s[x] = s[x-1]\n \n return count\n``` | 34 | 2 | [] | 5 |
minimum-number-of-moves-to-make-palindrome | Two pointer | C++ | two-pointer-c-by-zuks_100-wlnw | \nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int n = s.length();\n \n int left = 0, right = s.size() - 1, ans = 0 | zuks_100 | NORMAL | 2022-03-05T16:18:28.486994+00:00 | 2022-03-05T16:19:58.413110+00:00 | 3,595 | false | ```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int n = s.length();\n \n int left = 0, right = s.size() - 1, ans = 0;\n while (left < right) {\n int l = left, r = right;\n while (s[l] != s[r]) r--; \n if (l == r) {\n // here we hit the odd element\n swap(s[r], s[r + 1]);\n ans++;\n continue;\n } else {\n // normal element\n while (r < right) swap(s[r], s[r + 1]), ans++, r++;\n }\n left++, right--;\n }\n return ans;\n }\n};\n``` | 26 | 1 | ['C', 'C++'] | 5 |
minimum-number-of-moves-to-make-palindrome | C++||Two Pointer Greedy Approach | ctwo-pointer-greedy-approach-by-be_quick-acb9 | \nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int n = s.length();\n int i =0,j=n-1;\n int ans = 0;\n whi | be_quick | NORMAL | 2022-03-05T16:41:15.524442+00:00 | 2022-03-05T17:06:56.791913+00:00 | 1,813 | false | ```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int n = s.length();\n int i =0,j=n-1;\n int ans = 0;\n while(i<j){\n if(s[i]==s[j]){ // Both Characters are same move 2 pointers\n i++;\n j--;\n }else{\n\t\t\t// Both characters are not same\n int found = -1;\n\t\t\t\t//find index nearest to j which matches with i index\n for(int k=j-1;k>i;k--){\n if(s[k]==s[i]){\n found = k;\n break;\n }\n }\n \n\t\t\t\t// found the character which is equal to s[i]\n if(found>0){\n for(int k=found;k<j;k++){\n swap(s[k],s[k+1]);\n ans++;\n }\n i++;\n j--;\n }else{\n\t\t\t\t/* If not found means that character at ith index would have been odd character.\n\t\t\t\tso swap it so it would eventually end at middle of string*/\n swap(s[i],s[i+1]);\n ans++;\n }\n \n }\n }\n return ans;\n }\n};\n``` | 16 | 0 | ['Two Pointers', 'Greedy', 'C++'] | 3 |
minimum-number-of-moves-to-make-palindrome | [Python] with proof for why move a from the form of a....a.... to a.......a works | python-with-proof-for-why-move-a-from-th-zrh2 | Proof\nProvide with a not very solid but acceptable proof:\n\n(1) let\'s convert the string to an array to \nexample: "abcab" -> ["a", "b", "c", "a", "b"]\n\n(2 | cathatino | NORMAL | 2022-03-05T19:45:40.838763+00:00 | 2022-03-06T06:07:01.764600+00:00 | 1,910 | false | # Proof\nProvide with a not very solid but acceptable proof:\n\n(1) let\'s convert the string to an array to \nexample: `"abcab"` -> `["a", "b", "c", "a", "b"]`\n\n(2) let\'s only consider to move `first element` to be Palindrome. In our example\n\nit will be to move from the form of\n`["a", ..., "a", ...]`\nlet\'s assume between first `"a"` and last `"a"` there are number of x elements and behind last `"a"` we have number of y elements\n`"a", ..., "a", ...` = `"a", arr_with_length_x, "a", array_with_length_y`\n`"a", arr_with_length_x, "a", array_with_length_y` -> `"a", arr_with_length_x, array_with_length_y, "a"`\n\nAs first `"a"` is at start of string so to move last `"a"` to the end of string, it takes y moves.\n\nLet\'s consider to make another kinds of `Palindrome`, i.e. we move first `"a"` to index d (in the form of `[..., "a", ..., "a", ...]`)\n`"a", arr_with_length_x, "a", array_with_length_y` -> `arr_with_length_d, "a", arr_with_length_x_minus_d, arr_with_length_y_minus_d, "a", arr_with_length_d`\nthen for first `"a"`, it takes `d` moves and relatively it takes `y-d` moves for last `"a"`, thus it is `d`+`y-d` = `y` moves in total\n\ni.e. no difference on moves count if just want to make `"a"` Palindrome\n\n(3) let\'s compare two kinds forms, which is better? \n**3.1.** `"a", arr_with_length_d, arr_with_length_x_minus_d, arr_with_length_y_minus_d, arr_with_length_d, "a"`\n**3.2.** `arr_with_length_d, "a", arr_with_length_x_minus_d, arr_with_length_y_minus_d, "a", arr_with_length_d`\nIt is obvious 3.1. is better (min moves) coz, from (2) we already proof to move `"a"`, 3.1. and 3.2. both takes `y` moves\nAnd on form of **3.2.**, if to move element in `arr_with_length_d` out of itself , it will defintely pass by `"a"` and thus always requires one more extra moves than the **3.1.**\n\n## Examples for (3)\nLet\'s start with `axxayy`\n\n### using 3.1. \n`axxayy` -> `axxyya` (2 moves)\nthen this equilvalent to move `xxyy` to Palindrome\n\n`xxyy` -> `xyyx` (2 moves)\n\n### using 3.2.\n`axxayy` -> `xxaayy` (same as 3.1. it is 2 moves as proof in (2))\nMoving `xxaayy` -> `xyaayx` it takes:\n`xxaayy` -> `xaayyx` (4moves) when moving x to last, x swap with `a` two times\n`xaayyx` -> `xyaayx` (2moves) when moving y to index 1,y swaps with `a` two times\n\ntotally 6 moves = original 2 moves (same as in `3.1.`) + 4 moves (swaps with by `a` 4 times)\n# Solution\nProvide with a recursive solution using above greedy solution\n\n```\nclass Solution(object):\n def minMovesToMakePalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n count, length_of_s = 0, len(s)\n if length_of_s <= 2:\n return count\n for i in reversed(range(length_of_s)):\n if s[i] != s[0]:\n continue\n if i == 0:\n\t\t\t\t# move to middle is a speical case which takes len(s)/2 moves then do recursive for remaining part\n count += len(s)/2 + self.minMovesToMakePalindrome(s[1:]) \n else:\n\t\t\t # this move takes len(s)-1 - i (move from i to last index len(s)-1)and then do recursive for remaining part\n count += len(s)-1-i + self.minMovesToMakePalindrome(s[1:i]+s[i+1:])\n break\n return count\n``` | 12 | 0 | ['Greedy', 'Recursion', 'Python'] | 1 |
minimum-number-of-moves-to-make-palindrome | Clean Java Code With Explanation | clean-java-code-with-explanation-by-subh-xb84 | Check if the character in start and end index are same if yes then decrease the end by 1 and increase the start by 1\n Otherwise search for the character simila | subham_99 | NORMAL | 2022-08-23T05:22:58.981409+00:00 | 2022-08-23T05:22:58.981452+00:00 | 1,652 | false | * **Check if the character in start and end index are same if yes then decrease the end by 1 and increase the start by 1**\n* **Otherwise search for the character similar to the starting index by decrementing the end** \n* **If it is seen that on decrementing the end it points to same index as start then swap the character with the character in the next index and increment the ans count**\n\n* **Otherwise check the last index pointer is less than the ending indx if yes then increase it as well as increase the ans and keep on swapping the last index pointer with its next position.**\n\n***Please Upvote if you like my approach***\n```\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n \n int ans = 0;\n \n int start = 0 , end = s.length() - 1;\n \n char ch[] = s.toCharArray();\n \n while(start < end)\n {\n \n int r = end;\n \n if(ch[start] == ch[end])\n {\n start++;\n end--;\n continue;\n }\n \n while(ch[start] != ch[r])\n {\n r--; \n }// aabb l is pointing at 0 th index while r is pointing to b which is not equal to a so r-- by doing this we are searching whether any a is present there other than the one which l is pointing\n \n if(start == r) // means no a is present other than first index\n {\n //swap them\n \n swap(ch,r,r+1);\n ans++;\n \n }\n else \n {\n while(r<end)\n {\n swap(ch,r,r+1);\n ans++;\n r++;\n }\n \n }\n \n \n }\n return ans;\n }\n \n private void swap(char ch[] , int i , int j)\n {\n \n char c = ch[i];\n ch[i] = ch[j];\n ch[j] = c;\n \n }\n} | 10 | 0 | ['Two Pointers', 'Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ Greedy solution with explanation | c-greedy-solution-with-explanation-by-na-yly1 | Approach:\nWhen do you say that the string is Palindrome?\nWhen it reads same forward and backward right.\nThis is what we will try to do in this approach.\n\nW | naman-1234 | NORMAL | 2022-03-08T18:57:10.365152+00:00 | 2022-03-08T18:58:10.278011+00:00 | 1,281 | false | ## Approach:\nWhen do you say that the string is Palindrome?\nWhen it reads same forward and backward right.\nThis is what we will try to do in this approach.\n\nWe will go with same approach.\n- We will go with first half of the elements and see if their corresponding character from last is equal, If it is equal then we move on to next character.\n- If it is not we will find the pos of the nearest character from right which is same as given character.\n\t- Now there are two subcases:\n\t- If that position is equal to the idx itself, This means we are at odd index, Reason is since we are given a palindrome is always possible, So if this would not have been the case we would have found the position in right. In this case we will just swap it with the next element and increase the counter. For the sake of understanding, Take example of **"abb"** we will make it **"bab"** with 1 swap.\n\t- If it is not then we have to swap each consecutive element from the position we found from the right, To make characters equal at that particular position.\n\n## Code:\n```\n int minMovesToMakePalindrome(string s) {\n int l,r,n,cnt=0;\n n=s.length();\n l=0;\n r=n-1;\n \n while(l<r){\n if(s[l] == s[r]){\n l++;\n r--;\n continue;\n }\n \n int idx=r;\n while(idx>l && s[idx] != s[l])\n idx--;\n \n if(idx == l){\n // This means odd case, Just swap it with itself and do not need to go further\n swap(s[idx], s[idx+1]);\n cnt++;\n continue;\n }\n \n while(idx<r){\n swap(s[idx],s[idx+1]);\n cnt++;\n idx++;\n }\n l++;\n r--;\n }\n return cnt;\n }\n```\n\n**Hope you like it!!\nPlease do upvote it if you like it and let me know if there are any mistakes/questions in the comments below \uD83D\uDC47\uD83D\uDC47 .** | 10 | 0 | ['Greedy', 'C', 'C++'] | 1 |
minimum-number-of-moves-to-make-palindrome | C++ solutions | c-solutions-by-infox_92-j7fg | \nclass Solution {\nprivate:\n void swap(string& s, int i, int j){\n char t = s[i];\n s[i] = s[j];\n s[j] = t;\n }\npublic:\n int | Infox_92 | NORMAL | 2022-11-21T11:55:29.530938+00:00 | 2022-11-21T11:55:29.530973+00:00 | 1,137 | false | ```\nclass Solution {\nprivate:\n void swap(string& s, int i, int j){\n char t = s[i];\n s[i] = s[j];\n s[j] = t;\n }\npublic:\n int minMovesToMakePalindrome(string s) {\n int ans = 0, l = 0, r = s.size() - 1;\n \n while(l < r){\n if(s[l] == s[r]){\n l++; r--;\n continue;\n }\n \n int r_ = r;\n while(s[r_] != s[l]){\n r_--;\n }\n\n if(r_ == l){\n ans += s.size() / 2 - l;\n l++;\n }else{\n ans += r - r_;\n while(r_ < r){\n swap(s, r_, r_ + 1);\n r_++;\n }\n l++; r--;\n }\n }\n return ans;\n }\n};\n``` | 8 | 0 | ['C++'] | 1 |
minimum-number-of-moves-to-make-palindrome | JAVA | EASY | EXPLANATION | TWO POINTER | java-easy-explanation-two-pointer-by-bha-sybs | class Solution {\n public int minMovesToMakePalindrome(String s) {\n \n char []arr=s.toCharArray();\n int start=0;\n int n=s.leng | bharat0512 | NORMAL | 2022-03-24T18:54:02.638019+00:00 | 2022-06-30T05:20:41.868891+00:00 | 1,942 | false | class Solution {\n public int minMovesToMakePalindrome(String s) {\n \n char []arr=s.toCharArray();\n int start=0;\n int n=s.length();\n int end=s.length()-1;\n int res=0;\n while(start<end)\n {\n int k=end;\n // if we found pal char \n if(arr[start]==arr[end])\n {\n start++;\n end--;\n continue; \n }\n // char is not pal we will search particular char\n // towards starting point\n // because it is the right way to make min moves\n // then we will swap\n // and return the answer\n while(arr[start]!=arr[k])\n {\n k--;\n \n }\n if(k==start)\n {\n res++;\n swap(arr,start,start+1);\n }\n else\n {\n while(k<end)\n {\n res++;\n swap(arr,k,k+1);\n k++;\n }\n }\n }\n \n return res;\n }\n \n \n public static void swap(char arr[],int i,int j)\n {\n char temp=arr[i];\n arr[i]=arr[j];\n arr[j]=temp;\n }\n \n} | 7 | 0 | ['Java'] | 3 |
minimum-number-of-moves-to-make-palindrome | [Python] simple solution with graphic explanation | python-simple-solution-with-graphic-expl-nx4x | start from the first letter. we can tell that its corresponding position is the last index n - 1. Search for the right most same letter and swap it to the targe | huayu_ivy | NORMAL | 2022-03-05T16:07:01.504229+00:00 | 2022-03-05T16:17:33.794117+00:00 | 1,287 | false | * start from the first letter. we can tell that its corresponding position is the last index `n - 1`. Search for the right most same letter and swap it to the target position\n\n\n* if we cannot find a same letter, this letter should be placed at center. We can skip it for now.\n\n\n* keep iterating\n\n\n* finally, we swap the unique letter to center\n\n\ncode:\n```\ndef minMovesToMakePalindrome(self, s: str) -> int:\n ans = 0\n n = len(s)\n target = n - 1 # 0\'s corresponding index\n for i in range(math.ceil(n / 2)):\n for j in range(target, i - 1, -1):\n # search backward\n if j == i:\n # occurrance is 1, needs to be placed at center\n ans += n // 2 - i\n elif s[i] == s[j]:\n s = s[:j] + s[j + 1 : target + 1] + s[j] + s[target + 1:]\n ans += target - j\n target -= 1\n break\n return ans\n``` | 7 | 0 | ['Python'] | 1 |
minimum-number-of-moves-to-make-palindrome | C++ || Two Pointer || Easy Understanding | c-two-pointer-easy-understanding-by-gnan-zcar | class Solution {\npublic:\n\n int minMovesToMakePalindrome(string s) {\n int n=s.size();\n int p=0;\n int q=n-1;\n int ans=0;\n | GnanaPrakash9 | NORMAL | 2022-07-11T06:08:08.494556+00:00 | 2022-10-02T12:15:00.907328+00:00 | 2,289 | false | class Solution {\npublic:\n\n int minMovesToMakePalindrome(string s) {\n int n=s.size();\n int p=0;\n int q=n-1;\n int ans=0;\n int y=-1;\n while(p<=q)\n {\n if(s[p]!=s[q])\n {\n int temp=q-1;\n while(s[temp]!=s[p])\n temp--;\n if(temp!=p)\n {\n for(int i=temp;i<q;i++)\n {\n swap(s[i],s[i+1]);\n ans++;\n }\n }\n else\n {\n y=p;\n q++;\n }\n }\n p++;\n q--;\n }\n if(y!=-1) // If the frequency of a particular letter is odd\n { // Only at most one letter can have odd frequency\n ans+=abs(s.size()/2-y); // This is the required swaps to bring that letter to the middle\n }\n return ans;\n }\n}; | 6 | 0 | ['Two Pointers', 'Greedy', 'C++'] | 3 |
minimum-number-of-moves-to-make-palindrome | Without considering any odd element case using two pointer method | without-considering-any-odd-element-case-ceyz | Hello guys,\nthis is a simple solution for Minimum Number of Moves to Make Palindrome problem\n\nLet l=0, r=n-1\n\nif(s[l]==s[r]) l++,r--;\n\nelse\n{\nsearch s | aakaxh | NORMAL | 2022-06-11T11:41:28.754921+00:00 | 2022-06-11T11:42:01.808868+00:00 | 289 | false | **Hello guys,**\nthis is a simple solution for `Minimum Number of Moves to Make Palindrome` problem\n\nLet `l=0, r=n-1`\n\n`if(s[l]==s[r]) l++,r--;`\n\n`else`\n`{`\nsearch s[l] from right side of the string \nand seach s[r] from left side of the string\n\nlet we get `s[l]` at `idx2` from right then there will be` r-idx2` swaps required\nand for we get `s[r]` at `idx1` from left then there will be `idx1-l` swaps required\n\nwe will take swap action from min distance and pull that particular character to `l` or `r`\n`}`\n\n**Code:**\n```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n \n int n=s.size();\n int l=0,r=n-1;\n \n int cnt=0;\n while(l<r)\n {\n if(s[l]==s[r])\n {\n l++,r--;\n }\n else\n {\n int idx1=l,idx2=r;\n \n // left search\n char c=s[r];\n for(int i=l+1;i<n;++i)\n {\n if(s[i]==c)\n {\n idx1=i; break;\n }\n }\n \n // right search\n c=s[l];\n for(int i=r-1;i>=0;i--)\n {\n if(s[i]==c) {\n idx2=i; break;\n }\n }\n \n // swap \n if(idx1-l<=r-idx2)\n {\n while(idx1>l)\n {\n swap(s[idx1],s[idx1-1]);\n idx1--;\n \n cnt++;\n }\n }\n else\n {\n while(idx2<r)\n {\n swap(s[idx2], s[idx2+1]);\n idx2++;\n \n cnt++;\n }\n }\n \n l++,r--;\n }\n }\n \n return cnt;\n }\n};\n```\n\nThanks... | 5 | 0 | ['Two Pointers'] | 1 |
minimum-number-of-moves-to-make-palindrome | [C++] Runtime: 8 ms, faster than 99.93% | Memory: 6.6 MB, less than 98.24% | c-runtime-8-ms-faster-than-9993-memory-6-xfm8 | \nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int ans = 0;\n \n while(s.length() > 0){\n int n = s | anubhabishere | NORMAL | 2022-03-08T06:00:57.477170+00:00 | 2022-03-08T06:00:57.477214+00:00 | 456 | false | ```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int ans = 0;\n \n while(s.length() > 0){\n int n = s.length();\n char c = s[n-1];\n int ind = s.find(c);\n //cout<<s<<" "<<ind<<" "<<c<<endl;\n if(ind == n-1){\n ans += n/2;\n s.pop_back();\n } else {\n ans += ind;\n s.pop_back();\n s.erase(ind,1);\n }\n }\n \n return ans;\n }\n};\n``` | 5 | 0 | ['Array', 'String', 'C'] | 1 |
minimum-number-of-moves-to-make-palindrome | C# | Memory beats 100.00%, Runtime beats 77.78% [EXPLAINED] | c-memory-beats-10000-runtime-beats-7778-7droc | Intuition\nThe problem requires us to rearrange characters to form a palindrome, which means that characters at symmetric positions should match. To minimize th | r9n | NORMAL | 2024-09-19T19:37:34.727183+00:00 | 2024-09-19T19:37:34.727219+00:00 | 60 | false | # Intuition\nThe problem requires us to rearrange characters to form a palindrome, which means that characters at symmetric positions should match. To minimize the number of swaps, we can perform a greedy approach by finding the best positions for each character and then swapping it into place.\n\n\n# Approach\nTwo-Pointer Technique: We\'ll use two pointers, one starting from the left (at index 0) and one from the right (at index n-1).\n\n\nMatching Characters: For each character from the left, find the corresponding character from the right. If they don\'t match, move the right pointer inward by swapping adjacent characters until the characters match.\n\n\nCenter Character: If the string length is odd, there will be one unmatched center character that can remain as it is.\n\n\nMinimizing Moves: The fewer swaps we make, the better. The goal is to move the mismatched characters in place with the fewest adjacent swaps.\n\n\n# Complexity\n- Time complexity:\nO(n^2) in the worst case because we might have to perform swaps for each character in the string.\n\n- Space complexity:\nO(1), since we are modifying the input array in place and using a constant amount of extra space.\n\n# Code\n```csharp []\npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n char[] arr = s.ToCharArray();\n int n = arr.Length;\n int left = 0, right = n - 1;\n int moves = 0;\n\n while (left < right) {\n if (arr[left] == arr[right]) {\n left++;\n right--;\n } else {\n int r = right;\n // Find the character matching arr[left] on the right side\n while (r > left && arr[r] != arr[left]) {\n r--;\n }\n \n if (r == left) {\n // Special case: left character needs to move to the center\n Swap(arr, left, left + 1);\n moves++;\n } else {\n // Swap until the character at r is moved to the right position\n while (r < right) {\n Swap(arr, r, r + 1);\n r++;\n moves++;\n }\n // Now arr[left] and arr[right] are matching, move inward\n left++;\n right--;\n }\n }\n }\n\n return moves;\n }\n\n private void Swap(char[] arr, int i, int j) {\n char temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}\n\n``` | 4 | 0 | ['C#'] | 0 |
minimum-number-of-moves-to-make-palindrome | BRUTE FORCE || C++ | brute-force-c-by-ganeshkumawat8740-pzq4 | Code\n\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int i = 0, j = s.length()-1,k,ans=0;\n while(i<j){\n | ganeshkumawat8740 | NORMAL | 2023-06-10T11:23:03.544464+00:00 | 2023-06-10T11:23:14.491216+00:00 | 1,119 | false | # Code\n```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int i = 0, j = s.length()-1,k,ans=0;\n while(i<j){\n if(s[i]==s[j]){\n i++;j--;\n }else{\n k = j;\n while(k>=i && s[k] != s[i]){\n k--;\n }\n if(k==i){\n ans++;\n swap(s[i],s[i+1]);\n }else{\n while(k<j){\n swap(s[k],s[k+1]);\n k++;\n ans++;\n }\n i++;j--;\n }\n }\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Two Pointers', 'String', 'Greedy', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | c++ superfast 92% solution | c-superfast-92-solution-by-shrest-6gus | \nclass Solution {\npublic:\n int solve(string &s,char target,int last,int index)\n {\n int pos=-1;\n for(int i=last;i>=0;i--)\n {\n | SHREST | NORMAL | 2022-03-12T08:29:51.685561+00:00 | 2022-03-12T09:37:57.875120+00:00 | 560 | false | ```\nclass Solution {\npublic:\n int solve(string &s,char target,int last,int index)\n {\n int pos=-1;\n for(int i=last;i>=0;i--)\n {\n if(s[i]==target)\n {\n pos=i;\n break;\n }\n }\n int c=0;\n\t\t//if my string is "abb" and hence i got same pos of a from last and from end then return c i.e 0\n if(pos==index)return c;\n while(pos!=last)\n {\n swap(s[pos],s[pos+1]);\n pos++;\n c++;\n }\n return c;\n }\n int minMovesToMakePalindrome(string s) \n {\n int ans=0;\n int n=s.size();\n int res=0;\n\t\t//for even\n for(int i=0;i<n/2;i++)\n {\n if(s[i]!=s[n-1-i])\n {\n int ch=solve(s,s[i],n-1-i,i);\n if(ch==0)\n {\n ans=INT_MAX;\n break;\n }\n res+=ch;\n }\n }\n\t\t//for odd and my single element is in left\n if(n&1 && ans==INT_MAX)\n {\n ans=0;\n reverse(s.begin(),s.end());\n for(int i=0;i<n/2;i++)\n {\n if(s[i]!=s[n-1-i])\n {\n int ch=solve(s,s[i],n-1-i,-1);\n ans+=ch;\n }\n }\n return ans+res;\n }\n return res;\n }\n};\n``` | 4 | 0 | ['Greedy', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | Explanation - logical proof why greedy works | explanation-logical-proof-why-greedy-wor-rz8e | This may not be a concrete proof but atleast having some idea is better than nothing. I could not find any good explanation out there, so please comment here if | niranjvin | NORMAL | 2022-03-05T16:35:18.754782+00:00 | 2022-03-05T16:36:49.213232+00:00 | 552 | false | This may not be a concrete proof but atleast having some idea is better than nothing. I could not find any good explanation out there, so please comment here if you have found a better resource :)\n\n\nYou might have already read the approach - \n1. initialise left and right pointers to 0 and size-1 respectively\n2. find character to the left of right pointer which is equal to character at l and modify the string. If not found return -1 (handle odd length string case as well)\n\nWhy does this work? Why is it enough replace just 1 character (either to the left or right), could there be a better solution by replacing both characters ?\n\nThink about this - No matter what you do, in order to align 2 characters in the given string, it would taken a min of swaps depending on the following 2 values - pos(right), pos(left) .i.e. in the end you will end up making these many swaps for sure for these 2 characters.\n\nNow, you can notice that in our method we are exaclty doing this - making a minimum number of swaps. .i.e. moving one of the left or the right character by this minimum number of swaps.\n\n```\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n \n int count = 0;\n int l = 0;\n int r = s.length()-1;\n \n StringBuilder sb = new StringBuilder(s);\n \n int skip = 0;\n \n while(l<r){\n \n char leftChar = sb.charAt(l); \n char rightChar = sb.charAt(r);\n int temp = r; \n \n while(l < temp && leftChar != sb.charAt(temp)){\n temp--;\n }\n \n if(l == temp){\n if(s.length()%2 == 0){\n return -1;\n } else {\n if(skip == 1) return -1;\n skip = 1;\n count = count + s.length()/2 - l;\n l = l + 1;\n }\n continue;\n }\n \n count = count + r - temp;\n \n sb.deleteCharAt(temp);\n sb.insert(r, leftChar);\n \n \n r--;\n l++;\n \n }\n \n\n \n return count;\n \n }\n}\n``` | 4 | 1 | ['Greedy', 'Java'] | 1 |
minimum-number-of-moves-to-make-palindrome | c++ easy swap solution | c-easy-swap-solution-by-lovelydays95-154o | C++\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int res = 0;\n for(int i = 0, j = s.length() - 1; i < s.length() / | lovelydays95 | NORMAL | 2022-03-05T16:01:53.518933+00:00 | 2022-03-05T16:02:31.573231+00:00 | 499 | false | ```C++\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int res = 0;\n for(int i = 0, j = s.length() - 1; i < s.length() / 2; i++, j--) {\n if(s[i] == s[j]) continue;\n int f = j - 1;\n for(; f >= i; f--) { //find closest character\n if(s[i] == s[f]) break;\n }\n if(f == i) { //if closest character is at s[i], s[i] should move to middle of s\n res += s.length() / 2 - i;\n j++;\n } else { //else, calculate distance and swap all characters\n res += j - f;\n for(; f < j; f++) {\n swap(s[f], s[f+1]);\n }\n }\n }\n return res;\n }\n};\n``` | 4 | 0 | [] | 0 |
minimum-number-of-moves-to-make-palindrome | Python Greedy 2 pointer | python-greedy-2-pointer-by-shubhamnishad-plt4 | \tclass Solution:\n\t\tdef minMovesToMakePalindrome(self, s: str) -> int:\n\t\t\ts = list(s) #makes it easy for assignment op\n\n\t\t\tres = 0\n\t\t\tleft, righ | shubhamnishad25 | NORMAL | 2022-09-12T18:18:42.523984+00:00 | 2022-09-12T18:18:42.524023+00:00 | 925 | false | \tclass Solution:\n\t\tdef minMovesToMakePalindrome(self, s: str) -> int:\n\t\t\ts = list(s) #makes it easy for assignment op\n\n\t\t\tres = 0\n\t\t\tleft, right = 0, len(s) - 1\n\n\t\t\twhile left < right:\n\t\t\t\tl, r = left, right\n\n\t\t\t\t#find matching char\n\t\t\t\twhile s[l] != s[r]:\n\t\t\t\t\tr -= 1\n\n\t\t\t\t# if index dont match then swap\n\t\t\t\tif l != r:\n\t\t\t\t\t# swap one by one\n\t\t\t\t\twhile r < right:\n\t\t\t\t\t\ts[r], s[r + 1] = s[r + 1], s[r]\n\t\t\t\t\t\tres += 1\n\t\t\t\t\t\tr += 1\n\n\t\t\t\telse:\n\t\t\t\t\ts[r], s[r + 1] = s[r + 1], s[r]\n\t\t\t\t\tres += 1\n\t\t\t\t\tcontinue # get outside the main while loop\n\n\t\t\t\tleft += 1\n\t\t\t\tright -= 1\n\n\t\t\treturn res | 3 | 0 | ['Python', 'Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | JAVA SOLUTION || STRING BUILDER || GREEDY || TWO POINTER | java-solution-string-builder-greedy-two-jc525 | \nclass Solution {\n public int minMovesToMakePalindrome(String s) \n {\n int n=s.length();\n StringBuilder sb=new StringBuilder(s);\n | 29nidhishah | NORMAL | 2022-08-20T14:54:22.144708+00:00 | 2022-08-20T14:54:22.144748+00:00 | 838 | false | ```\nclass Solution {\n public int minMovesToMakePalindrome(String s) \n {\n int n=s.length();\n StringBuilder sb=new StringBuilder(s);\n int ans=0;\n \n while(sb.length()>1)\n {\n char ch=sb.charAt(0);\n int pos=sb.lastIndexOf(ch+"");\n \n if(pos==0)\n ans+=n/2;\n \n else\n {\n ans+=n-pos-1;\n sb.deleteCharAt(pos);\n n--;\n }\n \n sb.deleteCharAt(0);\n n--;\n }\n \n return ans;\n }\n}\n``` | 3 | 0 | ['String', 'Greedy', 'Java'] | 3 |
minimum-number-of-moves-to-make-palindrome | Faster || Easy To Understand || C++ Code | faster-easy-to-understand-c-code-by-__kr-cy60 | Using Greedy Approach\n\n Time Complexity : O(N * N)\n Space Complexity : O(1)\n\n\nint minMovesToMakePalindrome(string str) {\n \n int n = str.si | __KR_SHANU_IITG | NORMAL | 2022-04-03T14:32:45.353613+00:00 | 2022-04-03T14:32:45.353663+00:00 | 563 | false | * ***Using Greedy Approach***\n\n* ***Time Complexity : O(N * N)***\n* ***Space Complexity : O(1)***\n\n```\nint minMovesToMakePalindrome(string str) {\n \n int n = str.size();\n \n int low = 0;\n \n int high = n - 1;\n \n int count = 0;\n \n while(low <= high)\n {\n if(str[low] == str[high])\n {\n low++;\n \n high--;\n }\n else\n {\n int idx = high - 1;\n \n while(idx > low)\n {\n if(str[low] == str[idx])\n {\n break;\n }\n \n idx--;\n }\n \n if(idx == low)\n {\n count++;\n \n swap(str[idx], str[idx + 1]);\n }\n \n else\n {\n while(idx < high)\n {\n count++;\n \n swap(str[idx], str[idx + 1]);\n \n idx++;\n }\n }\n }\n }\n \n return count;\n }\n``` | 3 | 1 | ['Greedy', 'C'] | 1 |
minimum-number-of-moves-to-make-palindrome | Java | Greedy | Two pointers | java-greedy-two-pointers-by-pratham_ghul-69sl | \nclass Solution {\n public int minMovesToMakePalindrome(String str) {\n int n=str.length();\n char[] s=str.toCharArray();\n int lptr=0; | pratham_ghule | NORMAL | 2022-03-07T10:21:57.318784+00:00 | 2022-03-07T10:21:57.318813+00:00 | 710 | false | ```\nclass Solution {\n public int minMovesToMakePalindrome(String str) {\n int n=str.length();\n char[] s=str.toCharArray();\n int lptr=0;\n int rptr=n-1;\n \n int res=0;\n while(lptr<rptr){\n int r=rptr;\n \n if(s[lptr]==s[r]){\n lptr++;\n rptr--;\n continue;\n }\n \n while(s[lptr]!=s[r]) r--;\n \n if(lptr==r){\n swap(s,lptr,lptr+1);\n res++;\n }\n else{\n while(r!=rptr){\n swap(s,r,r+1);\n r++;\n res++;\n }\n }\n }\n return res;\n }\n \n public void swap(char[] s,int l,int r){\n char temp=s[l];\n s[l]=s[r];\n s[r]=temp;\n }\n}\n``` | 3 | 0 | ['Greedy', 'Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | Java O(n log n) Solution with Binary Index Trees | java-on-log-n-solution-with-binary-index-krab | \nclass Solution {\n List<Integer> [] charList;\n int [][] charPointers;\n int [] BIT;\n \n public int minMovesToMakePalindrome(String s) {\n | profchi | NORMAL | 2022-03-05T16:53:54.779581+00:00 | 2022-03-05T16:53:54.779606+00:00 | 926 | false | ```\nclass Solution {\n List<Integer> [] charList;\n int [][] charPointers;\n int [] BIT;\n \n public int minMovesToMakePalindrome(String s) {\n \n charList = new List[26];\n charPointers = new int [26][2];\n BIT = new int [s.length()];\n \n for (int i = 0; i < 26; ++i){\n charList[i] = new ArrayList<>();\n }\n \n for (int i = 0; i < s.length(); ++i)\n charList[s.charAt(i) - \'a\'].add(i);\n \n for (int i = 0; i < 26; ++i){\n charPointers[i][0] = 0;\n charPointers[i][1] = charList[i].size() - 1;\n }\n \n int l = 0;\n int lP, rP;\n char c;\n int result = 0;\n int currentIdx;\n boolean [] visited = new boolean [s.length()];\n \n int mid = s.length() / 2;\n \n for (int r = s.length() - 1; r > l; --r){\n if (visited[r]) continue;\n \n c = s.charAt(r);\n \n lP = charList[c - \'a\'].get(charPointers[c - \'a\'][0]++);\n rP = charList[c - \'a\'].get(charPointers[c - \'a\'][1]--);\n \n visited[lP] = true;\n visited[rP] = true;\n \n if (lP == rP){\n result += Math.max(mid , 0);\n addToBIT(lP);\n continue;\n }\n \n result += lP - getBITVal(lP);\n addToBIT(lP);\n --mid;\n }\n \n return result;\n }\n \n private void addToBIT(int val){\n ++val;\n \n for (int i = val; i < BIT.length; i += (i & -i)){\n ++BIT[i];\n }\n }\n \n private int getBITVal(int val){\n val++;\n int result = 0;\n \n for (int i = val; i > 0; i -= (i & -i)){\n result += BIT[i];\n }\n \n return result;\n }\n}\n``` | 3 | 1 | ['Greedy', 'Binary Indexed Tree'] | 2 |
minimum-number-of-moves-to-make-palindrome | Beats 97.75% || C++ || Greedy | beats-9775-c-greedy-by-akash92-iod7 | Intuition\n Describe your first thoughts on how to solve this problem. \nTo make a string a palindrome, matching pairs of characters should be placed symmetrica | akash92 | NORMAL | 2024-10-02T15:49:16.133225+00:00 | 2024-10-02T15:49:35.502239+00:00 | 274 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo make a string a palindrome, matching pairs of characters should be placed symmetrically from the start and end. For each character at the back, we look for its matching character in the remaining part of the string, move it to the correct position, and then remove both characters (one from the front and one from the back) once they are paired. The process repeats until the string becomes empty. In case of an odd-length palindrome, the middle character doesn\u2019t need to be moved but contributes to the total number of operations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tWe start by identifying the last character in the string (s.back()) and find its first occurrence from the front of the string using s.find(s.back()).\n2.\tIf the first occurrence is the same as the last character (ind == s.size()-1), it means the last character is a middle character in an odd-length palindrome, so we account for the moves it would take to place it in the middle (ind/2).\n3.\tIf it\u2019s not the middle character, we calculate how many moves it would take to bring this matching character to the correct position at the back by adding ind to ans.\n4.\tWe then remove this matching character from the front (s.erase(ind,1)) and also remove the last character (s.pop_back()), since it has been paired.\n5.\tRepeat this process until the string is empty.\n6.\tThe function returns the total number of moves needed to make the string a palindrome.\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int ans = 0;\n\n while(s.size()){\n int ind = s.find(s.back());\n if(ind == s.size()-1) ans += ind/2; // middle element\n else{ // non-middle element\n ans += ind;\n s.erase(ind,1); // assume it to be front, and delete the front since it is matched now\n }\n \n s.pop_back(); // delete the back, since it is matched now\n }\n\n return ans;\n }\n};\n\nauto speedup = [](){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }();\n``` | 2 | 0 | ['String', 'Greedy', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | 🧧Easy Understandable C++ Solution || Greedy + Two-Pointers | easy-understandable-c-solution-greedy-tw-pkkd | Intuition + Approach\n- We basically try to convert the second half of the string into the first half.\n- To do this, We greedily pick the closest element to th | teqarine | NORMAL | 2023-07-18T21:15:55.710016+00:00 | 2023-07-18T21:15:55.710042+00:00 | 74 | false | # Intuition + Approach\n- We basically try to convert the second half of the string into the first half.\n- To do this, We greedily pick the closest element to the right pointer and swap it until we reach its correct position, i..e.. (n-i-1).\n- An edge case will be when the length of the string is odd and there\'s a character which occurs an odd number of times, and then this odd character should be present in the middle of the whole string.\n- To do this, if the character is found at the same index as the left pointer, then we just shift it by one to the right,so that it comes in the middle eventually.\n\n# Complexity\n- Time complexity: O(n*n) worst case\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) , constant space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n> \uD83C\uDF86Upvote\uD83C\uDF86\n\n---\n\n\n\n# Code\n```\nclass Solution {\npublic:\n\n int minMovesToMakePalindrome(string s){\n int left=0,right=s.size()-1;\n int out=0;\n\n while(left<right){\n if(s[left]==s[right]){\n left++;\n right--;\n }\n else{\n int r=right-1;\n while(s[left]!=s[r])r--;\n if(r==left){\n swap(s[r],s[r+1]);\n out++;\n }\n else{\n while(r<right){\n swap(s[r],s[r+1]);\n out++;\n r++;\n }\n left++;\n right--;\n }\n }\n }\n\n return out;\n }\n};\n```\n\n | 2 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Intuition Made Easy for you | C++ Explanation | intuition-made-easy-for-you-c-explanatio-kjpn | ```\nint solve(string s)\n {\n int n=s.size(),ans=0,i=0,j=n-1;\n \n while(iWe are fixing the first half and changing 2nd half accordin | kunalrautela | NORMAL | 2022-10-29T11:40:09.409145+00:00 | 2022-10-29T11:40:09.409190+00:00 | 98 | false | ```\nint solve(string s)\n {\n int n=s.size(),ans=0,i=0,j=n-1;\n \n while(i<j)\n {\n if(s[i]!=s[j])\n {\n //Step 1 ->We are fixing the first half and changing 2nd half according to it \n \n int idx=j;\n while(s[idx]!=s[i]) //j se i ki trf aao aur dekho kaunsa idx s[i] ke equal\n idx--;\n \n //Step 2 -> special case like "ahbbaaa" here h should come in middle so just swap with its next element and (NO i++,j-- here as process krna baaki hai use to ab "abhbaaa" is string me process kro NO i++ and j--)\n \n if(i==idx) \n {\n swap(s[idx],s[idx+1]);\n ans++;\n continue; //IMPORTANT --> No i++ and j-- for special case\n }\n \n //Step 3 -> Agar koi milgya hume s[i] ke equal to use hume jth place tk lana to idx<j jab tk hai tb tk swap marte rho aur ans++ krdo\n \n else\n {\n while(idx<j)\n {\n swap(s[idx],s[idx+1]);\n idx++; ans++;\n }\n }\n }\n \n i++;\n j--; //i aur j position match krwadi ab aage bdo \n }\n return ans;\n }\n int minMovesToMakePalindrome(string s) {\n \n return solve(s);\n } | 2 | 0 | [] | 1 |
minimum-number-of-moves-to-make-palindrome | C++||Two Pointers||Easy to Understand | ctwo-pointerseasy-to-understand-by-retur-75o8 | ```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s)\n {\n int n=s.size(),i=0,j=n-1,ans=0;\n int yes=-1;\n while(i | return_7 | NORMAL | 2022-09-06T00:33:10.969680+00:00 | 2022-09-06T00:33:10.969739+00:00 | 736 | false | ```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s)\n {\n int n=s.size(),i=0,j=n-1,ans=0;\n int yes=-1;\n while(i<j)\n {\n if(s[i]!=s[j])\n {\n int temp=j-1;\n while(s[temp]!=s[i])\n temp--;\n if(i!=temp)\n {\n for(int k=temp+1;k<=j;k++)\n {\n swap(s[k-1],s[k]);\n ans++;\n }\n }\n else\n {\n yes=i;\n j++;\n }\n }\n i++;\n j--;\n }\n if(yes!=-1)\n {\n ans+=((s.size())/2-yes);\n }\n return ans;\n }\n};\n//if you like the solution plz upvote. | 2 | 0 | ['Two Pointers', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ | Short and Simple Greedy Solution | c-short-and-simple-greedy-solution-by-dh-awdx | \n\n int minMovesToMakePalindrome(string s) {\n int n = s.size(), ans = 0;\n while(n)\n {\n int i = 0;\n while(s[i | dhakad_g | NORMAL | 2022-08-20T04:54:51.062942+00:00 | 2022-08-20T04:54:51.062987+00:00 | 409 | false | \n```\n int minMovesToMakePalindrome(string s) {\n int n = s.size(), ans = 0;\n while(n)\n {\n int i = 0;\n while(s[i] != s[n-1]) i++;\n if(i == n-1) ans += (n-1)/2;\n else ans += i, s.erase(s.begin()+i),n--;\n s.pop_back();\n n--;\n }\n return ans;\n }\n``` | 2 | 0 | ['Greedy', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | Easy Two-Pointer C++ method (75% faster) | easy-two-pointer-c-method-75-faster-by-s-2jeo | \n int minMovesToMakePalindrome(string s) {\n int n=s.size();\n int i=0;\n int j=n-1;\n int cnt=0;\n int centre_ele=-1;\n | sxkshi | NORMAL | 2022-08-13T12:26:50.083064+00:00 | 2022-08-17T02:20:58.067126+00:00 | 612 | false | ```\n int minMovesToMakePalindrome(string s) {\n int n=s.size();\n int i=0;\n int j=n-1;\n int cnt=0;\n int centre_ele=-1;\n int left,right;\n while(i<=j)\n {\n //non-matching elements\n if(s[i]!=s[j])\n {\n left=i+1;\n while(s[left]!=s[j] && left<j)\n {\n left++;\n }\n \n //odd element found -> to be made middle element\n if(left==j)\n {\n \n centre_ele=j;\n j--;\n continue;\n }\n \n else\n {\n for(int k=left;k>i;k--)\n {\n swap(s[k],s[k-1]);\n cnt++;\n }\n }\n \n }\n //normal matching elements\n else\n {\n i++;\n j--;\n }\n }\n \n \n \n if(centre_ele!=-1)\n {\n cnt+=centre_ele -(n / 2);\n }\n \n return cnt;\n \n }\n``` | 2 | 0 | ['Two Pointers', 'C', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Python3] peel the string | python3-peel-the-string-by-ye15-vfaz | \n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n ans = 0 \n while len(s) > 2: \n lo = s.find(s[-1])\n | ye15 | NORMAL | 2022-06-14T19:50:47.489222+00:00 | 2022-06-14T19:50:47.489331+00:00 | 1,044 | false | \n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n ans = 0 \n while len(s) > 2: \n lo = s.find(s[-1])\n hi = s.rfind(s[0])\n if lo < len(s)-hi-1: \n ans += lo \n s = s[:lo] + s[lo+1:-1]\n else: \n ans += len(s)-hi-1\n s = s[1:hi] + s[hi+1:]\n return ans\n``` | 2 | 0 | ['Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ | TWO-POINTERS | implementation | c-two-pointers-implementation-by-chikzz-2plq | PLEASE UPVOTE IF U LIKE MY SOLUTION AND EXPLANATION :\')\n\n\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n \n int n= | chikzz | NORMAL | 2022-03-07T17:01:44.081160+00:00 | 2022-03-07T17:01:44.081194+00:00 | 237 | false | **PLEASE UPVOTE IF U LIKE MY SOLUTION AND EXPLANATION :\')**\n\n```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n \n int n=s.length();\n int left=0,right=n-1;\n int res=0;\n \n while(left<right)\n {\n int l=left,r=right; \n while(s[l]!=s[r])\n l++;//traversing from the left in search of the same ele as s[r]\n \n //if we do not get another occurence of s[r] i.e., there is only one instance and hence it will be the middle ele\n //we swap s[l] with the previous char to check whether another instance of that char is present so that we can \n //swap to make a valid palindromic string\n \n if(l==r)\n {\n //on doing this repeatedly for each window we have the single char at s[l] and finally at the last\n //iteration l will point to the middle of the string and hence the single ele will be placed at the middle of the\n //string resulting into a valid palindromic string\n \n swap(s[l-1],s[l]);\n res++;\n //here we do not decrease the size of the current window \n //for checking once again in the same window\n continue;\n }\n else\n {\n while(l>left)\n {\n swap(s[l-1],s[l]);\n res++;\n l--;\n }\n }\n //swap is done and hence we are sure that s[left]==s[right]\n //now we decrease the size of the window from both the sides and do the same process again\n left++;\n right--;\n }\n \n return res;\n }\n};\n``` | 2 | 0 | ['Two Pointers'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Python] Easy And Good Solution. | python-easy-and-good-solution-by-laxmina-jud7 | let\'s take one example: let s = "letelt". we have two cases where final s can start with l or final s can end with t. we calculate moves for both of them. for | laxminarayanak | NORMAL | 2022-03-06T02:26:28.003121+00:00 | 2022-03-06T15:24:45.154842+00:00 | 773 | false | **let\'s take one example:** let ```s = "letelt"```. we have two cases where final ```s``` can start with ```l``` or final ```s``` can end with ```t```. we calculate moves for both of them. for final ```s``` starts with ```l``` takes 1 swap(i.e letetl) and for final ```s``` ends with ```t``` takes two swap (i.e tleelt). starting with ```l``` is minimun so continue the process recursion with deleting both start and end letter of s. \n\n**TIME COMPLEXITY**:\n```O(n*n)```\n\n**code**\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n \n @lru_cache(None)\n def check(w):\n\t\t#base case\n if w==w[::-1]:\n return 0\n ans=0\n\t\t#if already both ends are equal\n if w[0]==w[-1]:\n return check(w[1:-1])\n else:\n wi=w[::-1]\n\t\t\t\t#i=first letter of word\n i=w[0]\n\t\t\t\t#j is the last letter of the word\n j=wi[0]\n\t\t\t\t#k is the no of swaps to make in w of j letter. This is fo checking swap with ending case\n k=w.index(j)\n\t\t\t\t#swaps for starting case\n z=wi.index(i)\n\t\t\t\t#final words after deleting\n q=w[:k]+w[k+1:-1]\n a=wi[:z]+wi[z+1:-1]\n #checking greedy\n if k<z:\n ans+=check(q)+k\n else:\n ans+=check(a)+z\n return ans\n return check(s)\n```\n**Please Upvote! I Really Appreciate it If You Upvote.**\n | 2 | 0 | ['Dynamic Programming', 'Greedy', 'Python'] | 0 |
minimum-number-of-moves-to-make-palindrome | Accepted Easy Java Solution | accepted-easy-java-solution-by-himanshus-klcj | \nclass Solution {\n public static boolean isValid(String s) {\n int[] counter = new int[26];\n int oddCount = 0;\n for (int i = 0; i < | himanshushekar | NORMAL | 2022-03-05T16:09:41.227244+00:00 | 2022-03-05T16:10:59.357890+00:00 | 473 | false | \nclass Solution {\n public static boolean isValid(String s) {\n int[] counter = new int[26];\n int oddCount = 0;\n for (int i = 0; i < s.length(); i++) {\n counter[s.charAt(i) - \'a\']++;\n }\n for (int value : counter) {\n if (value % 2 != 0) {\n oddCount++;\n }\n }\n return oddCount <= 1;\n }\n public int minMovesToMakePalindrome(String ss) {\n int n = ss.length();\n char s[] = ss.toCharArray();\n int count = 0;\n for (int i = 0; i < n / 2; i++) {\n int left = i;\n int right = n - left - 1;\n while (left < right) {\n if (s[left] == s[right]) {\n break;\n } else {\n right--;\n }\n }\n if (left == right) {\n // s[left] is the character in the middle of the palindrome\n char t = s[left];\n s[left] = s[left + 1];\n s[left + 1] = t;\n count++;\n i--;\n } else {\n for (int j = right; j < n - left - 1; j++) {\n char t = s[j];\n s[j] = s[j + 1];\n s[j + 1] = t;\n count++;\n }\n }\n }\n return count;\n }\n \n} | 2 | 3 | ['Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | Segment tree Solution | O(NLogN) | segment-tree-solution-onlogn-by-viditgup-pep7 | IntuitionI am assuming you are aware with how this could be solved using the brute way in O(n^2). The main problem with that approach is to track the indices af | viditgupta7001 | NORMAL | 2025-03-08T21:38:34.079979+00:00 | 2025-03-08T21:38:34.079979+00:00 | 59 | false | # Intuition
I am assuming you are aware with how this could be solved using the brute way in O(n^2). The main problem with that approach is to track the indices after making swaps. If we are somehow able to track the correct position of indices, we can find the first occurence of a character to the left or right of an index in logarithmic time.
So, rather than changing the positions after making a swap, track all the available indices in their respective order as they appear.
eg.
"letelt"
Right now every position is turned on.
i.e in the base level I have something like 111111 in my segment tree.
Let's say you decide to keep s[0] same and make s[n-1] = s[0]. Then you need an 'l' to appear at n-1.
You saw that the nearest occurence of that exist at index 4.
So in your segment tree, you mark the index 0 and index 4 as off.
i.e it now becomes something like
011101
The node in my segment tree stores the sum of all the indices turned on
through seg[index].sum and seg[index].v denotes the frequency of characters in the range. This frequency will allow you to find the first of the last character position in the given range in log(n) time.
Two functions take care of it.
flindex: finds first occurence of character c in the range [l,r]
llindex: finds last occurence of character c in the range [l,r]
query: gives me the number of **on** indices in the range which helps me to correctly evaluate the number of swaps needed.
update: turns off the position
findKthOne: gives me the kth position of on bit in the range.
findKthOne(1). Will give me l and findKthOne(numberOfOnes in [0,n]) will give me r.
Where l and r are the correct positions I need to match. Treat it the same as two pointers i and j but this time after having made the swaps.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Segtree{
private:
struct Node{
int sum;
vector<int>v;
Node(){
sum = 0;
v.resize(26,0);
}
};
int size;
vector<Node>seg;
public:
Segtree(int n){
size = 1;
while(size < n)size *= 2;
seg.resize(size * 4);
}
Node merge(Node &left,Node &right){
Node res;
res.sum = left.sum + right.sum;
for(int i=0;i<26;i++)res.v[i] = left.v[i] + right.v[i];
return res;
}
void build(int index,int lx,int rx,string &s){
if(rx-lx==1){
if(lx < s.size()){
seg[index].sum = 1;
seg[index].v[s[lx]-'a'] = 1;
}
return;
}
int mid = (lx + rx)/2;
build(2*index+1,lx,mid,s);
build(2*index+2,mid,rx,s);
seg[index] = merge(seg[2*index+1],seg[2*index+2]);
}
void build(string &s){
build(0,0,size,s);
}
int findKthOne(int index,int lx,int rx,int k){
if(rx-lx==1){
return lx;
}
int mid = (lx + rx)/2;
if(seg[2*index+1].sum >= k)return findKthOne(2*index+1,lx,mid,k);
return findKthOne(2*index+2,mid,rx,k-seg[2*index+1].sum);
}
int findKthOne(int k){
return findKthOne(0,0,size,k);
}
void update(int index,int lx,int rx,int idx){
if(rx-lx==1){
seg[index] = Node();
return;
}
int mid = (lx + rx)/2;
if(idx < mid)update(2*index+1,lx,mid,idx);
else update(2*index+2,mid,rx,idx);
seg[index] = merge(seg[2*index+1],seg[2*index+2]);
}
void update(int idx){
update(0,0,size,idx);
}
int flindex(int index,int lx,int rx,int l,int r,char c){
if(seg[index].v[c-'a']==0 || rx<=l || lx>=r)return -1;
if(rx-lx==1){
return lx;
}
int mid = (lx + rx)/2;
int res = flindex(2*index+1,lx,mid,l,r,c);
if(res==-1){
res = flindex(2*index+2,mid,rx,l,r,c);
}
return res;
}
int flindex(int l,int r,char c){
return flindex(0,0,size,l,r,c);
}
int llindex(int index,int lx,int rx,int l,int r,char c){
if(seg[index].v[c-'a']==0 || rx<=l || lx>=r)return -1;
if(rx-lx==1){
return lx;
}
int mid = (lx + rx)/2;
int res = llindex(2*index+2,mid,rx,l,r,c);
if(res==-1){
res = llindex(2*index+1,lx,mid,l,r,c);
}
return res;
}
int llindex(int l,int r,char c){
return llindex(0,0,size,l,r,c);
}
int query(int index,int lx,int rx,int l,int r){
if(lx>=l && rx<=r)return seg[index].sum;
if(rx<=l || lx>=r)return 0;
int mid = (lx + rx)/2;
int left = query(2*index+1,lx,mid,l,r);
int right = query(2*index+2,mid,rx,l,r);
return left + right;
}
int query(int l,int r){
return query(0,0,size,l,r);
}
};
class Solution {
public:
int minMovesToMakePalindrome(string s) {
int n = s.size(),ans = 0;
Segtree sg(n);
sg.build(s);
while(true){
int ones = sg.query(0,n);
if(ones<=1)break;
int firstIndex = sg.findKthOne(1),lastIndex = sg.findKthOne(ones);
if(s[firstIndex]==s[lastIndex]){
sg.update(firstIndex);
sg.update(lastIndex);
continue;
}
int occIndex1 = sg.llindex(firstIndex+1,lastIndex+1,s[firstIndex]);
int cost1 = (occIndex1==-1) ? INT_MAX: sg.query(occIndex1,lastIndex);
int occIndex2 = sg.flindex(firstIndex,lastIndex,s[lastIndex]);
int cost2 = (occIndex2==-1) ? INT_MAX: sg.query(firstIndex+1,occIndex2+1);
if(cost1 < cost2){
sg.update(firstIndex);
sg.update(occIndex1);
}
else{
sg.update(lastIndex);
sg.update(occIndex2);
}
ans+=min(cost1,cost2);
}
return ans;
}
};
``` | 1 | 0 | ['Two Pointers', 'Greedy', 'Segment Tree', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Simple two pointer approach || edge case explained | simple-two-pointer-approach-edge-case-ex-vqb7 | IntuitionApproachUsing two pointers to check each character from start and end of string.Edge CaseIn case a string is of odd length, there can be one character | sakshecodes | NORMAL | 2024-12-02T06:25:53.097767+00:00 | 2024-12-14T16:29:12.102068+00:00 | 185 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing two pointers to check each character from start and end of string.\n\n# Edge Case\nIn case a string is of odd length, there can be one character (center character), which will not have a duplicate in the string.\nUsing a variable centerIndex to keep track of this character\'s original position.\nOnce we have tracked the whole string, we only need to add the number of swaps required to push centerIndex at center of the string.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n char[] str = s.toCharArray();\n int left = 0; int right = str.length-1; int count = 0; int endindex = right;\n int centerIndex = -1;\n\n while (left < right) {\n if (str[left] == str[right]) {\n left++;\n right--;\n continue;\n }\n\n endindex = right;\n\n while (str[left] != str[right]) {\n right--;\n }\n\n if (right == left) {\n centerIndex = left;\n left++;\n right = endindex;\n continue;\n }\n\n while (right != endindex) {\n swap(str, right, right+1);\n right++;\n count++;\n }\n\n\n right--;\n left++;\n }\n\n if (centerIndex != -1) {\n System.out.println(centerIndex);\n // swaps to reach centre of the string\n count += Math.abs(centerIndex - str.length/2);\n }\n\n return count;\n }\n\n public void swap(char[] str, int left, int right) {\n char c = str[left];\n str[left] = str[right];\n str[right] = c;\n return;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | Easy Approach!! With Explanation !! Upvote | easy-approach-with-explanation-upvote-by-js9d | 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 | Pratheesha | NORMAL | 2024-08-28T18:38:37.606576+00:00 | 2024-08-28T18:38:37.606608+00:00 | 17 | 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:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n \nint minMovesToMakePalindrome(string s) {\n int moves = 0;\n int left = 0, right = s.length() - 1;\n \n while (left < right) {\n // If the characters at both ends are the same, move inward\n if (s[left] == s[right]) {\n left++;\n right--;\n } else {\n // Find the matching character for the left side\n int l = right;\n while (l > left && s[l] != s[left]) {\n l--;\n }\n \n // If the character at \'l\' matches the character at \'left\'\n if (l == left) {\n // Special case: No matching character on the right side\n swap(s[left], s[left + 1]);\n moves++;\n } else {\n // Move the matching character to the \'right\' position\n for (int i = l; i < right; i++) {\n swap(s[i], s[i + 1]);\n moves++;\n }\n // Move inward after the swap\n left++;\n right--;\n }\n }\n }\n \n return moves;\n}\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | ✅Easy C++ Soln || With Explanation || Optimized Soln || Two-Pointers || With Comments | easy-c-soln-with-explanation-optimized-s-2s7g | \n int minMovesToMakePalindrome(string s) {\n \n int st = 0, end = s.length()-1,ans=0;\n \n while(st<end){\n \n | tanishsingla13390 | NORMAL | 2024-06-11T11:53:57.589071+00:00 | 2024-06-11T11:53:57.589103+00:00 | 33 | false | ```\n int minMovesToMakePalindrome(string s) {\n \n int st = 0, end = s.length()-1,ans=0;\n \n while(st<end){\n \n int l = st, r = end;\n \n // if first and last elements are not equal\n // then we will move until we find the equal element (as first ele)\n // in this case we are changing the second half(to make it pallindrome)\n // we can do the same by changing first half also\n //but in both case result will be same\n while(s[l]!=s[r])r--;\n \n // this means that the element we encounter is the middle element\n // ex :- abb\n // l = 0, r = 0\n // as we only have one a\n //in this case we will try to move this element to middle.\n if(l==r){\n swap(s[r],s[r+1]);\n ans++;\n continue;\n }else{\n // same element as first element is found..\n //then we will swap till end (until first element became equal to last element)\n while(r<end)swap(s[r],s[r+1]),ans++,r++;\n }\n \n st++,end--;\n }\n \n return ans;\n }\n\n\n``` | 1 | 0 | ['Greedy', 'C', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python (Simple Greedy) | python-simple-greedy-by-rnotappl-jjhe | 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 | rnotappl | NORMAL | 2024-05-23T12:45:36.444885+00:00 | 2024-05-23T12:45:36.444915+00:00 | 422 | 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:\n def minMovesToMakePalindrome(self, s):\n ans, count = list(s), 0 \n\n while ans:\n idx = ans.index(ans[-1])\n\n if idx == len(ans)-1:\n count += idx//2 \n else:\n count += idx \n ans.pop(idx)\n ans.pop()\n\n return count\n``` | 1 | 0 | ['Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | Java Optimize Solution with Some Minute Explanation | Interview Tricky Question | java-optimize-solution-with-some-minute-0fes2 | Complexity\n- Time complexity:O(n*k)\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# Co | Shree_Govind_Jee | NORMAL | 2024-02-06T03:33:50.888374+00:00 | 2024-02-06T03:33:50.888392+00:00 | 364 | false | # Complexity\n- Time complexity:$$O(n*k)$$\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 Solution {\n private int helper(char[] ch, int left, int temp) {\n while (left < temp) {\n if (ch[temp] == ch[left])\n return temp;\n\n temp--;\n }\n return temp;\n }\n\n private void swap(char[] ch, int left, int leftX) {\n if (leftX < ch.length) {\n char temp = ch[left];\n ch[left] = ch[leftX];\n ch[leftX] = temp;\n }\n }\n\n public int minMovesToMakePalindrome(String s) {\n char[] ch = s.toCharArray();\n int left = 0;\n int right = ch.length - 1;\n int moves = 0; // count of swapping made to make palindrom\n\n while (left < right) {\n if (ch[left] == ch[right]) {\n left++;\n right--;\n } else {\n int temp = right;\n temp = helper(ch, left, temp);\n if (temp == left) {\n moves++; // increament...\n swap(ch, left, left + 1);\n } else {\n while (temp < right) {\n swap(ch, temp, temp + 1);\n moves++; // increament...\n temp++;\n }\n left++;\n right--;\n }\n }\n }\n return moves;\n }\n}\n``` | 1 | 0 | ['Two Pointers', 'String', 'Greedy', 'Binary Indexed Tree', 'Java'] | 1 |
minimum-number-of-moves-to-make-palindrome | JS solution - Greedy + Merge Sort | js-solution-greedy-merge-sort-by-cutetn-buqm | \n\nPro tip: Love lil Xi\xE8 \uD83D\uDC9C \u7231\u5C0F\u8C22 \uD83D\uDC9C\nLike, seriously, how solutions with slice and split have better time smh that\'s weir | CuteTN | NORMAL | 2024-01-13T20:34:28.998468+00:00 | 2024-01-13T20:34:28.998497+00:00 | 310 | false | \n\nPro tip: Love lil Xi\xE8 \uD83D\uDC9C \u7231\u5C0F\u8C22 \uD83D\uDC9C\nLike, seriously, how solutions with `slice` and `split` have better time smh that\'s weird.\n\n# Complexity\n- let `n = s.length`; `m = alphabet size = 26`\n- Time complexity: $$O(n(logn + m))$$\n- Space complexity: $$O(n + m)$$\n\n# Code\n```js\nlet first = new Int16Array(26);\nlet target = new Int16Array(2000);\nlet msTemp = new Int16Array(2000);\n\nfunction mergeSort(l, r) {\n if (l >= r) return 0;\n\n let m = (l + r) >> 1;\n let inv = mergeSort(l, m) + mergeSort(m + 1, r);\n\n let li = l;\n let ri = m;\n\n for (; li <= m; ++li) {\n while (ri < r && target[ri + 1] < target[li]) ++ri \n inv += ri - m;\n }\n \n li = l;\n ri = m+1;\n for (let i = l; i <= r; i++) {\n if (li > m) msTemp[i] = target[ri++];\n else if (ri > r) msTemp[i] = target[li++];\n else if (target[li] < target[ri]) msTemp[i] = target[li++];\n else msTemp[i] = target[ri++];\n }\n for (let i = l; i <= r; i++) target[i] = msTemp[i];\n\n return inv;\n}\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar minMovesToMakePalindrome = function (s) {\n let n = s.length;\n let h = n >> 1;\n\n let cur = 0;\n\n first.fill(-1);\n target.fill(-1, 0, n);\n\n for (let i = n - 1; i >= 0; --i) {\n if (target[i] >= 0) continue;\n\n let c = s.charCodeAt(i) - 97;\n do {\n ++first[c];\n } while (s[first[c]] != s[i]);\n\n if (i === first[c]) {\n target[i] = h;\n } else {\n target[first[c]] = cur++;\n target[i] = n - cur;\n }\n }\n\n return mergeSort(0, n - 1);\n};\n``` | 1 | 0 | ['Two Pointers', 'String', 'Greedy', 'Merge Sort', 'JavaScript'] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ || Two Pointers || Greedy | c-two-pointers-greedy-by-nithish_9-xsdl | \n\n# Code\n\nclass Solution {\npublic:\n \n int minMovesToMakePalindrome(string s) {\n \n int low = 0;\n int high = s.length()-1;\n\ | Nithish_9 | NORMAL | 2023-08-07T07:10:56.430792+00:00 | 2023-08-07T07:10:56.430824+00:00 | 53 | false | \n\n# Code\n```\nclass Solution {\npublic:\n \n int minMovesToMakePalindrome(string s) {\n \n int low = 0;\n int high = s.length()-1;\n\n int count = 0;\n while (low<=high)\n {\n if (s[low] != s[high])\n {\n int i = high-1;\n while (i>=low+1)\n {\n if (s[low] == s[i])\n {\n break;\n }\n i--;\n }\n\n int j = low+1;\n while (j<=high-1)\n {\n if (s[high]==s[j])\n {\n break;\n }\n j++;\n }\n\n int d1 = high-i;\n int d2 = j-low;\n\n if (d1<=d2)\n {\n\n while (i<=high-1)\n {\n swap(s[i],s[i+1]);\n count++;\n i++;\n }\n }\n else\n {\n while (j>=low+1)\n {\n swap(s[j],s[j-1]);\n count++;\n j--;\n }\n }\n }\n low++;\n high--;\n }\n\n return count;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'Greedy', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Straightforward Greedy Algorithm in Python, Beating 100% | straightforward-greedy-algorithm-in-pyth-o82i | Approach\n Describe your approach to solving the problem. \nIn each turn, it is necessary to match the first character s[0] and the last charactor s[-1] of the | metaphysicalist | NORMAL | 2023-07-07T03:57:23.834551+00:00 | 2023-07-07T03:59:19.121850+00:00 | 115 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nIn each turn, it is necessary to match the first character `s[0]` and the last charactor `s[-1]` of the string `s`. Do nothing if the first and the last ones already match (i.e., `s[0] == s[-1]`). Otherwise, my greedy approach determines to replace the first or the last one by considering the cost. The cost to replace the first character `s[0]` is its distance to the leftmost occurrence of `s[-1]`; the cost to replace the last character `s[-1]` is its distance to the rightmost occurrence of `s[0]`. Pick up the choice with the lower cost and trim the first and the last characters from the string. \n\n# Complexity\n- Time complexity: $$O(n^2)$$, where $$n$$ is the length of the input string.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The input is $$O(n)$$. Only constant extra memeory is used.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n ans = 0\n while len(s) > 2:\n if s[0] != s[-1]:\n l, r = s.find(s[-1]), s.rfind(s[0])\n if l < len(s) - r - 1: \n ans += l\n s = s[:l] + s[l+1:-1]\n else:\n ans += len(s) - r - 1\n s = s[1:r] + s[r+1:]\n else:\n s = s[1:-1]\n return ans\n``` | 1 | 0 | ['String', 'Greedy', 'Python3'] | 1 |
minimum-number-of-moves-to-make-palindrome | Straightforward Brute-Force in Python, Beating 100% | straightforward-brute-force-in-python-be-1c8u | Approach\n Describe your approach to solving the problem. \nIn each turn, it is necessary to match the first character s[0] and the last charactor s[-1] of the | metaphysicalist | NORMAL | 2023-07-06T05:10:50.705405+00:00 | 2023-07-06T05:11:23.836018+00:00 | 203 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nIn each turn, it is necessary to match the first character `s[0]` and the last charactor `s[-1]` of the string `s`. Do nothing if the first and the last ones already match (i.e., `s[0] == s[-1]`). Otherwise, my greedy approach determines to replace the first or the last one by considering the cost. The cost to replace the first character `s[0]` is its distance to the leftmost occurrence of `s[-1]`; the cost to replace the last character `s[-1]` is its distance to the rightmost occurrence of `s[0]`. Pick up the choice with the lower cost and trim the first and the last characters from the string. \n\n# Complexity\n- Time complexity: $$O(n^2)$$, where $$n$$ is the length of the input string.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The input is $$O(n)$$. Only constant extra memeory is used.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n l, r = 0, len(s)-1\n ans = 0\n while len(s) > 2:\n if s[0] != s[-1]:\n nl, nr = s.find(s[-1]), s.rfind(s[0])\n if nl < len(s) - nr - 1: \n ans += nl\n s = s[:nl] + s[nl+1:-1]\n else:\n ans += len(s) - nr - 1\n s = s[1:nr] + s[nr+1:]\n else:\n s = s[1:-1]\n return ans\n``` | 1 | 0 | ['Two Pointers', 'String', 'Python3'] | 1 |
minimum-number-of-moves-to-make-palindrome | simple iterative solution | simple-iterative-solution-by-zaidokhla-mzng | Intuition\nin each iteration of the while loop(outer) we are solving a subproblem or trying to make the chars to be equal \nfor that we can either swap the s[l] | zaidokhla | NORMAL | 2023-04-27T08:56:41.996373+00:00 | 2023-04-27T08:56:41.996413+00:00 | 431 | false | # Intuition\nin each iteration of the while loop(outer) we are solving a subproblem or trying to make the chars to be equal \nfor that we can either swap the s[l] to next similar char on the right which is equal to s[r]\nor we can swap s[r] we the next similar char on the left which is equal to s[l] \neither way would work\n//since the ans is possible in every cases as mentioned by the question if we are unable to make chars similar at an index that the char will be the part of the middlwe of the pallindrome\nin inner while loops we are calculating the total nbumber of swaps\neach time we try to make the chars at l and r as equal \nafter each iteration of the outer while loop we only require to find the min swaps in s[lt..rt] as we have made the rest as pallindrome\nthis is some kind of a subproblem \nhere choosing the next first occrrence on the left or the right which can make the curr 2 as equal is the greedy approach here \nwhich works for the all the test cases\n\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 minMovesToMakePalindrome(string s) {\n \n\n //here we will be using an iterative recursive approach \n int lt=0;\n int rt=s.size()-1;\n int ans=0;\n //ans will keep track of the minimum number of swaps required to make it pallindrome in the most \n //optimal ways\n int l;\n int r;\n while(lt<rt){\n l=lt;\n r=rt;\n\n while(s[l]!=s[r])l++;\n //finding the first occurence from the right side which can make the current 2 characters equal\n if(l==r){\n //then it will be part of the odd length part in btw the whole pallindrome\n swap(s[l],s[l-1]);//here we will be using the internal c++ swapping function\n ans++;\n continue;\n }\n while(l>lt){\n swap(s[l],s[l-1]);\n l--;\n ans++;\n }\n lt++;\n rt--;\n \n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Full proof O(n) and O(1) C++ solution with in depth explaination | full-proof-on-and-o1-c-solution-with-in-2jw00 | Intuition\nSo the intuition behind this is that, if we can make the extreme elements (first and last index elements) of the string a palindrome taking optimal m | nutan_sangani | NORMAL | 2023-01-03T07:55:20.401804+00:00 | 2023-01-03T07:55:20.401855+00:00 | 98 | false | # Intuition\nSo the intuition behind this is that, if we can make the extreme elements (first and last index elements) of the string a palindrome taking optimal moves than we can recurse the algorithm on the substring from 2nd and 2nd last index, and so on and repeating this we can find the optimal no of moves.\n\nBut how to find the optimal moves for the first and last elements to be palindrome. This can be done by comparing which of the elements at last and first index is better suited for being the palindromic element.\n\nIf first and last elements are different, say first one is a and last one is b (a........b) than the substring can become palindromic with either choosing b or a at its extreme ends. ie a.......a or b.......b (where dots indicates all the elements in between the extreme ends). So now we have 2 options either to find another a from the string and make the last element a or to find another b from the string and to make the first element b.\n(we won\'t move first and last elements because we want to take least moves and thus we consider that atleast one of them is already palindromic)\n\nWe make the greedy choice here, we choose whichever elements is closer to the extremes, ie we want b at first index, so find after how many elements is another \'b\' from first element (to match it with the b at the other end) and similarly find after how many elements is another \'a\' from last element. (to match it with the a at the first index)\n\nIf b is closer, bring it to the first element or if a is closer, bring it to the last element. now we have a.....a or b.....b based on the closeness of same elements from both the ends. and thus the extremes of this substring are made palindromic and now consider the inner substring and do this recursively.\n\n# Why this works ??\nThis works because every time we are only bringing the similar element to the first or last index and rest all the elements are either right shifted (while bringing b to first index) or left shifted (while bringing a to last index) one space. Thus their order within the next smaller substring is not changed and we can again recurse them greedily. This would not be the case if we can move or swap any number with any other number, in that case the effect of swapping inner elements before choosing greedily would be different than after choosing greedily.\n\n# Walk through an example \ns = lleett\nso the extreme elements are l and t at index 0 and 5.\nthus finding the no of elements between 0 and next t, which is 3 and between index 5 and l is also 3. so we can make any one either l or t as the extreme elements in palindromic substring. we choose to make l as last element too.\ns = l(eett)l \n(we can see clearly here that the numbers between the extremes are just shifted to left side by 1 space and thier inner order has not changed.)\nnow considering the substring eett\nboth again have same distance from both ends, ie other t is 1 element away from first e and vice versa. we can again choose to move any one here.\nthus s = l(e(tt)e)l\nthus s is converted to a palindromic substring. and the swaps it takes is, distance swapped in pass one (ie 3)+1 and distance swapped in pass 2 (ie 1) + 1 = (3+1)+(1+1)=6.\n\ni hope you understood it, if yes than please upvote it.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\nwe can write this code recursively too it would be far better for understanding, so you can write it yourself to check your understanding of the problem, we have written if iteratively because it takes less space.\n```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int n=s.size();\n int left=0;\n int right=n-1;\n int count=0;\n int mid=n/2;\n for(int i=0;i<n/2;i++)\n {\n char a=s[left];\n char b=s[right];\n//finding the closest duplicate and swapping.\n if(a!=b)\n {\n int count1=0;\n for(int j=left+1;j<right;j++)\n {\n if(s[j]!=b)\n {\n count1+=1;\n }\n else break;\n }\n int count2=0;\n for(int j=right-1;j>left;j--)\n {\n if(s[j]!=a)\n {\n count2+=1;\n }\n else break;\n }\n if(count1>count2) //means that duplicate of a is\n //closer to right index of our window.\n {\n //now we will swap that duplicate till it reaches \n //till it reaches the right\'th index.\n int k=right-count2-1;\n//k stores the index of that duplicate no.\n count+=count2+1;\n while(k<right)\n {\n swap(s[k],s[k+1]);\n k++;\n }\n }\n else \n {\n//else either both have same distance or b is closer to left index,\n//in which case, we will swap it, till it reaches left\'th index\n int k=count1+1+left;\n//k stores the index of that duplicate no.\n count+=count1+1;\n while(k>left)\n {\n swap(s[k],s[k-1]);\n k--;\n }\n }\n\n }\n//decreasing the size of the subarray.\n left+=1;\n right-=1;\n }\n return count;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'String', 'Greedy', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | best solution | best-solution-by-riyuzaki7-j7uo | 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 | Riyuzaki7 | NORMAL | 2022-12-23T13:47:27.385787+00:00 | 2022-12-23T13:47:27.385825+00:00 | 102 | 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 minMovesToMakePalindrome(string s) {\n\n \n int result=0;\n int start=0,end=s.size()-1;\n\n while(end>start){\n if(s[start]!=s[end]){\n int i=end;\n while(i>start&&s[start]!=s[i]){\n i--;\n }\n if(i==start){\n swap(s[start],s[start+1]);\n result++;\n \n }\n else{\n while(i<end){\n swap(s[i],s[i+1]);\n result++;\n i++;\n }\n start++;\n end--;\n }\n }\n else{\n start++;\n end--;\n }\n }\n return result;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python + 2 pointers + Explanation. | python-2-pointers-explanation-by-rasnouk-ymjq | \n Add your space complexity here, e.g. O(n) \n\n# Code\n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n # At each point, we | rasnouk | NORMAL | 2022-11-13T22:46:16.709243+00:00 | 2022-11-13T22:46:16.709289+00:00 | 937 | false | \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n # At each point, we look at the first and the last elements\n # if they are the same, then we skip them, else we find\n # another element in the string that matches the left\n # element and then we make the necessary swaps to move it\n # to the right place. \n # if we can\'t find that element -- this means this is the middle element\n # in the palindrome, we just move it one position to the right and continue\n # over the next few iterations, it will be moved to the center automatically\n # run it for string = "dpacacp", answer should be 4\n # the character that should be in the middle is "d"\n l, r, res, st = 0, len(s)-1, 0, list(s)\n while l < r:\n if st[l] != st[r]:\n i = r\n while i > l and st[l] != st[i]:\n i -= 1\n if i == l:\n st[i], st[i+1] = st[i+1], st[i]\n res += 1\n continue\n else:\n while i < r:\n st[i], st[i+1] = st[i+1], st[i]\n i += 1\n res += 1\n l, r = l+1, r-1\n return res\n``` | 1 | 0 | ['Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Java Easy Solution w/ Comments] - Using Two Pointer Swapping | java-easy-solution-w-comments-using-two-nkr4w | Intuition\nJava Solution to Minimum Number of Moves To Make Palindrome. Uses a Two Pointer approach with swapping.\n\nIncluded comments for reference.\n\n# Comp | bjornmelin | NORMAL | 2022-10-03T22:02:57.139259+00:00 | 2022-10-03T22:02:57.139304+00:00 | 215 | false | # Intuition\nJava Solution to Minimum Number of Moves To Make Palindrome. Uses a Two Pointer approach with swapping.\n\nIncluded comments for reference.\n\n# Complexity\n- Time complexity: $$O(N^2)$$\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 Solution {\n\n public int minMovesToMakePalindrome(String s) {\n int len = s.length();\n if (len == 0) return -1;\n\n char[] chars = s.toCharArray(); // Init char array of all characters from s\n int swaps = 0; // int to store final number of swaps taken to make the palindrome\n\n // Use a two-pointer approach, initialize int pointer for left and right\n int left = 0;\n int right = len - 1;\n\n while (left < right)\n {\n // Found a palindrome\n if (chars[left] == chars[right])\n {\n left++; // Increment left pointer\n right--; // Decrement right pointer\n }\n // Characters are not palindrome\n else\n {\n // Search for character moving towards the starting point \'left\' to ensure\n // minimum number of moves until char at k matches char at \'left\'\n int k = right;\n k = findIndexMatchingLeftIndex(chars, left, k);\n\n // Character matching char at index \'left\' was not found between initial k index and left index\n if (k == left)\n {\n swaps++; // Increment swap count\n swapChars(chars, left); // Swap left with left + 1\n }\n // Character matching char at index \'left\' was found between initial k index and left index\n // Swap all characters from k to k + 1\n else\n {\n while (k < right)\n {\n swaps++;\n swapChars(chars, k);\n k++;\n }\n }\n }\n }\n\n // Return the number of swaps (Moves) needed to make the Palindrome\n return swaps;\n }\n\n /**\n * Swap Characters In The Character Array.\n */\n public void swapChars(char[] chars, int left) {\n // Swap chars[]\n if (left -1 < chars.length)\n {\n char temp = chars[left];\n chars[left] = chars[left + 1];\n chars[left + 1] = temp;\n }\n }\n\n /**\n * Finds The Kth Index In The Input char[] That Matches The Character At The Left Index Of The Input char[].\n */\n public int findIndexMatchingLeftIndex(char[] chars, int left, int k) {\n while (left < k)\n {\n if (chars[k] == chars[left])\n {\n return k;\n }\n k--; // Decrement k to compare with the previous index of the arr with left\n }\n\n return k;\n }\n}\n``` | 1 | 0 | ['Two Pointers', 'String', 'Binary Indexed Tree', 'Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Rust] Simple greedy solution | rust-simple-greedy-solution-by-wizist-ne1q | For any string with length > 1, check the number of moves required to make the string with equal leftmost and rightmost characters. Remove the leftmost and the | wizist | NORMAL | 2022-09-23T13:47:34.791451+00:00 | 2022-09-23T13:47:34.791494+00:00 | 300 | false | For any string with length > 1, check the number of moves required to make the string with equal leftmost and rightmost characters. Remove the leftmost and the rightmost characters. Repeat the procedure until the string length less than or equal to 1. The sum of all moves is the answer.\n\n```rust\nuse std::collections::*;\n \nimpl Solution {\n\tpub fn min_moves_to_make_palindrome(s: String) -> i32 {\n\t\tlet mut s = s.clone();\n\t\tlet mut ans = 0;\n\t\twhile s.len() > 1 {\n\t\t\tlet i = s.rfind(s.chars().nth(0).unwrap()).unwrap();\n\t\t\tif i != 0 {\n\t\t\t\tans += (s.len() - 1 - i) as i32;\n\t\t\t\ts = format!("{}{}", &s[1..i], &s[i + 1..]);\n\t\t\t} else {\n\t\t\t\tlet i = s.find(s.chars().last().unwrap()).unwrap();\n\t\t\t\tans += i as i32;\n\t\t\t\ts = format!("{}{}", &s[..i], &s[i + 1..(s.len() - 1)]);\n\t\t\t}\n\t\t}\n\t\tans\n\t}\n}\n``` | 1 | 0 | ['Greedy', 'Rust'] | 0 |
minimum-number-of-moves-to-make-palindrome | [python3] easy to understand 2 pointer solution with comments | python3-easy-to-understand-2-pointer-sol-dsfb | \n\'\'\'\nidea is to fix one side (left or right) and make other side equal to it\nfor e.g. \naabb , I will make right side equal to left.\n1. index[0] = a != i | kakarotssj11 | NORMAL | 2022-09-21T07:59:03.218578+00:00 | 2022-09-21T07:59:03.218616+00:00 | 654 | false | ```\n\'\'\'\nidea is to fix one side (left or right) and make other side equal to it\nfor e.g. \naabb , I will make right side equal to left.\n1. index[0] = a != index[3] = b \n2. now look for a from right to left \n3. once found swap with adjacent element till it reaches index[3].\n4. abba. is palindrome. took 2 swaps, \n\nfor cases like abb \n1. we fixed left side a. \n2. now from right we will move to left looking for a , we found it at index 0 which is our left\n3. now when left == right, just swap it with next adjacent element and continue.\n4. you will get your palindrome\n\n\'\'\'\n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = list(s)\n n = len(s)\n lt = 0\n rt = n-1\n ans = 0\n while lt < rt:\n l = lt\n r = rt\n while s[l] != s[r]:\n r -= 1\n # for abb like case\n # swap(s[r], s[r+1])\n # bab\n if l == r:\n s[r], s[r+1] = s[r+1], s[r]\n ans += 1\n continue\n else:\n\t\t\t# for aabb like case\n while r < rt:\n s[r], s[r+1] = s[r+1], s[r]\n ans += 1\n r += 1\n lt += 1\n rt -= 1\n return ans\n``` | 1 | 0 | ['Two Pointers', 'Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | java solution | java-solution-by-mrvishal_27-7xpc | \nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n int ans=0;\n char arr[]=s.toCharArray();\n int i=0; \n int | MrVishal_27 | NORMAL | 2022-09-20T23:54:17.730441+00:00 | 2022-09-20T23:54:17.730481+00:00 | 868 | false | ```\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n int ans=0;\n char arr[]=s.toCharArray();\n int i=0; \n int j=arr.length-1;\n while(i<j){\n int high=j;\n if(arr[i]==arr[j]){\n i++;\n j--;\n }\n else{\n while(arr[i]!=arr[high]){\n high--;\n }\n \n if(i==high) {\n swap(arr,high,high+1); // mid elememt\n ans++;\n continue;\n }\n \n else{\n \n while(high<j){ \n swap(arr,high,high+1);\n ans++;\n high++;\n }\n }\n }\n }\n return ans;\n \n }\n \n public static void swap(char ch[],int i,int j){\n \n char t=ch[i];\n ch[i]=ch[j];\n ch[j]=t;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python 2 pointer approach | python-2-pointer-approach-by-hemantdhami-mgui | \nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = list(s)\n res, left, right = 0, 0, len(s) - 1\n while left | hemantdhamija | NORMAL | 2022-09-05T07:23:38.366594+00:00 | 2022-09-05T07:23:38.366629+00:00 | 468 | false | ```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = list(s)\n res, left, right = 0, 0, len(s) - 1\n while left < right:\n l, r = left, right\n while s[l] != s[r]:\n r -= 1\n if l == r:\n s[r], s[r + 1] = s[r + 1], s[r]\n res += 1\n continue\n else:\n while r < right:\n s[r], s[r + 1] = s[r + 1], s[r]\n res += 1\n r += 1\n left += 1\n right -= 1\n return res\n``` | 1 | 0 | ['Two Pointers', 'Greedy', 'Python'] | 0 |
minimum-number-of-moves-to-make-palindrome | [C++] Simple C++ Code | c-simple-c-code-by-prosenjitkundu760-0i3h | Taken the help by master piece submission by\nhttps://leetcode.com/be_quick/\n\n# If you like the implementation then Please help me by increasing my reputation | _pros_ | NORMAL | 2022-09-03T18:13:18.636174+00:00 | 2022-09-03T18:14:02.281016+00:00 | 272 | false | **Taken the help by master piece submission by**\nhttps://leetcode.com/be_quick/\n\n# **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int i = 0, j = s.size()-1, ans = 0;\n while(i < j)\n {\n while(s[i] == s[j])\n {\n if(i >= j)\n return ans;\n i++;\n j--;\n }\n int indx = -1;\n for(int k = j-1; k > i; k--)\n {\n if(s[i] != s[k])\n continue;\n indx = k;\n break;\n }\n if(indx != -1)\n {\n for(int k = indx; k < j; k++)\n {\n swap(s[k], s[k+1]);\n ans++;\n }\n i++;\n j--;\n }\n else\n {\n swap(s[i], s[i+1]);\n ans++;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'Greedy', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | C# solution | c-solution-by-clewby-k7ys | \npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n List<char> list = s.ToList();\n int moves = 0;\n while(lis | clewby | NORMAL | 2022-09-01T06:16:36.524592+00:00 | 2022-11-04T18:54:52.325701+00:00 | 151 | false | ```\npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n List<char> list = s.ToList();\n int moves = 0;\n while(list.Count > 2){\n char target = list[0];\n int i = list.FindLastIndex(ch => ch == target);\n if(i != 0){\n moves += list.Count-i-1;\n list.RemoveAt(i);\n list.RemoveAt(0);\n } else{\n target = list[list.Count-1];\n i = list.FindIndex(ch => ch == target);\n moves += i;\n list.RemoveAt(list.Count-1);\n list.RemoveAt(i);\n }\n }\n return moves;\n }\n}\n``` | 1 | 0 | ['Greedy'] | 0 |
minimum-number-of-moves-to-make-palindrome | Java | O(NlogN) | Harder Variant of 1505. | java-onlogn-harder-variant-of-1505-by-st-ylrk | This question is the harder version of #1505 (link), so I can recommend that you do that problem first before coming back to this one. The idea is basically the | Student2091 | NORMAL | 2022-08-09T00:19:27.327582+00:00 | 2022-08-09T00:20:08.196018+00:00 | 725 | false | This question is the harder version of [#1505 (link)](https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits), so I can recommend that you do that problem first before coming back to this one. The idea is basically the same - to know what its actual position is, we need the prefix sum AND suffix sum of the characters we\'ve swapped.\n\nHere I am using 2 BIT arrays for the sake of simplicity. There are 2 cases, for the one we are switching to the head, denoted by `a` in my code below, it\'s cost needed is `L - i + (i - sum(head, L)) - sum(tail, L);`. \n> It translates to "Current index - current head position + all the characters behind it that moved to the head previously - all the characters ahead of it that moved to the tail` \n\nFor the one moving to tail, it needs `j - R + sum(tail, R) - (i - sum(head, R))`\n\n#### Java\n```Java\n// Time O(nlogn)\n// Space O(n)\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n char[] A = s.toCharArray();\n Deque<Integer>[] deque = new ArrayDeque[26];\n Arrays.setAll(deque, o -> new ArrayDeque<>());\n for (int i = 0; i < A.length; i++){\n deque[A[i]-\'a\'].offer(i);\n }\n int[] head = new int[A.length+1];\n int[] tail = new int[A.length+1];\n int i = 0, j = s.length()-1, ans = 0;\n while(i < j){\n int min = (int)1e9, idx = -1;\n for (int k = 0; k < 26; k++){\n if (deque[k].size()>=2){\n int L = deque[k].peekFirst(), R = deque[k].peekLast();\n int a = L - i + (i - sum(head, L)) - sum(tail, L);\n int b = j - R + sum(tail, R) - (i - sum(head, R));\n if (a+b < min){\n min=a+b;\n idx=k;\n }\n }\n }\n ans += min;\n add(head, deque[idx].pollFirst(), 1);\n add(tail, deque[idx].pollLast(), 1);\n i++;\n j--;\n }\n\n return ans;\n }\n\n private void add(int[] bit, int idx, int inc){\n for (++idx; idx < bit.length; idx += idx & -idx){\n bit[idx]+=inc;\n }\n }\n\n private int sum(int[] bit, int idx){\n int ans = 0;\n for (++idx; idx > 0; idx -= idx & -idx){\n ans += bit[idx];\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python simple recursion | 97% time | python-simple-recursion-97-time-by-dyc_9-ewac | \n def minMovesToMakePalindrome(self, s: str) -> int:\n n = len(s)\n if n <= 1:\n return 0\n if s[0]==s[-1]:\n ret | dyc_98 | NORMAL | 2022-08-05T21:51:03.190541+00:00 | 2022-08-05T21:51:03.190567+00:00 | 979 | false | ```\n def minMovesToMakePalindrome(self, s: str) -> int:\n n = len(s)\n if n <= 1:\n return 0\n if s[0]==s[-1]:\n return self.minMovesToMakePalindrome(s[1:-1])\n \n ind_l, ind_r = s.find(s[-1]), s.rfind(s[0])\n if ind_l <= n-1-ind_r:\n return ind_l + self.minMovesToMakePalindrome(s[:ind_l] + s[ind_l+1:-1])\n else:\n return n-1-ind_r + self.minMovesToMakePalindrome(s[1:ind_r] + s[ind_r+1:])\n``` | 1 | 0 | ['Greedy', 'Recursion', 'Python'] | 0 |
minimum-number-of-moves-to-make-palindrome | [C++] Two pointers approach | Easy to Understand | c-two-pointers-approach-easy-to-understa-h26h | \nclass Solution {\npublic:\n /*\n Two cases can come\n while we can compare first half with other half\n case 1 aabb -> a != b come back and se | amitesh46237242 | NORMAL | 2022-07-09T16:50:56.579591+00:00 | 2022-07-09T16:50:56.579619+00:00 | 264 | false | ```\nclass Solution {\npublic:\n /*\n Two cases can come\n while we can compare first half with other half\n case 1 aabb -> a != b come back and see if we find a , we finally find an \'a\' at aa so swap it till we bring it at end to match , abab swap again abba, now a==a now its turn of b and its matching so we return swaps=2\n case 2 - odd number of chars abb , a!=b search for a, we finally get a at a itself which means its the only character in the string so swap it with next index\n abb->bab and continue your search , b==b so swaps=1 ans\n */\n int minMovesToMakePalindrome(string s) {\n int left=0;\n int right=s.size()-1;\n int ans=0;\n while(left<right)\n {\n int l=left;\n int r=right;\n \n //while you not find char same a first element continue decreasing right index\n while(s[l]!=s[r])\n {\n r--;\n }\n //case 2 ->single element found\n if(l==r)\n {\n swap(s[r],s[r+1]);\n ans++;\n continue;\n }\n else\n {\n while(r<right)\n {\n swap(s[r],s[r+1]);\n ans++;\n r++;\n }\n }\n left++;\n right--;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ Easy Solution | Greedy | c-easy-solution-greedy-by-rac101ran-or9o | \nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int cnt = 0;\n while(!s.empty()) {\n int other = s.find( | rac101ran | NORMAL | 2022-07-07T01:17:09.120460+00:00 | 2022-07-07T01:17:09.120506+00:00 | 253 | false | ```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int cnt = 0;\n while(!s.empty()) {\n int other = s.find(s.back());\n if(other==s.size()-1) {\n // odd ?\n cnt+=other/2; // move it to the middle \n }else {\n cnt+=other;\n s.erase(other,1); // delete char at positon \n }\n s.pop_back();\n }\n return cnt;\n }\n};\n``` | 1 | 0 | ['Greedy', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | USING TWO POINTER || SIMPLEST SOLUTION | using-two-pointer-simplest-solution-by-k-bdey | \n int i=0;\n int j=s.size()-1;\n int l=0;\n int r=s.size()-1;\n int cnt=0;\n while(l<r){\n if(s[l]==s[r])\n | kranti1 | NORMAL | 2022-06-24T14:52:04.189288+00:00 | 2022-06-24T14:52:04.189325+00:00 | 320 | false | ```\n int i=0;\n int j=s.size()-1;\n int l=0;\n int r=s.size()-1;\n int cnt=0;\n while(l<r){\n if(s[l]==s[r])\n {\n l++;\n r--;\n continue;\n }\n i=l;\n j=r;\n while(s[j]!=s[i]){\n j--;\n }\n swap(s[j],s[j+1]);\n cnt++; \n }\n \n return cnt;\n``` | 1 | 0 | ['C'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python || 2 Pointers || Greddy | python-2-pointers-greddy-by-in_sidious-77bf | Make first half equal to second half greedily!!\n\n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n n=len(s)\n s=list(s | iN_siDious | NORMAL | 2022-06-03T14:05:26.374973+00:00 | 2022-06-03T14:05:26.375006+00:00 | 801 | false | Make first half equal to second half greedily!!\n\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n n=len(s)\n s=list(s)\n l,r=0,n-1\n ans=0\n while (l<r):\n ll,rr=l,r\n while (s[ll]!=s[rr]): rr-=1\n if (ll==rr): # found a middle element in an odd palindrome\n s[rr],s[rr+1]=s[rr+1],s[rr]\n ans+=1\n continue\n else:\n while (rr<r): \n s[rr],s[rr+1]=s[rr+1],s[rr]\n rr+=1\n ans+=1\n l+=1\n r-=1\n return ans\n``` | 1 | 0 | ['Greedy', 'Python'] | 0 |
minimum-number-of-moves-to-make-palindrome | Very Easy Solution With Proper Comments | C++ | very-easy-solution-with-proper-comments-8wd1n | \nclass Solution {\npublic:\n \n /**\n \n observation->we only need to move one of two characters of the palindrome string at minimum cost\n \n | sumer47kumar | NORMAL | 2022-05-22T14:31:51.886209+00:00 | 2022-05-22T14:31:51.886263+00:00 | 637 | false | ```\nclass Solution {\npublic:\n \n /**\n \n observation->we only need to move one of two characters of the palindrome string at minimum cost\n \n \n move from left to right\n try to find and swap the character according scanning from right to left\n -> from required position to left\n \n in case of odd length of the string you may find a unpaired character which you have to store in the center of the string.\n -> you can ignore it if it is present on the right side of the string because it will adjust itself automatically \n -> but if it is on the left side \n just reverse the string and pass in the same function\n */\n \n int solve(string &a)\n { \n int size = a.size();\n \n int cnt=0;\n \n //traverse only the half of the string \n for(int i=0;i<size/2;i++)\n {\n \n int ind=-1;\n \n //searching for other pair right to left from required position-> size-1-i \n for(int j=size-1-i;j>i;j--)\n {\n //break if found\n if(a[i]==a[j]){\n ind=j;\n break;\n }\n }\n \n //in case of unpaired character \n //reverse the string and pass to same function\n //just to move that unpaired character to right part\n if(ind==-1)\n {\n reverse(a.begin(),a.end());\n return cnt+solve(a);\n }\n \n //add the difference of indexes (actual index to required index) in the cound\n cnt += size-1-i-ind;\n \n //modify the string accordingly\n for(int j=ind;j<size-1-i;j++)\n {\n swap(a[j],a[j+1]);\n }\n }\n return cnt;\n }\n \n int minMovesToMakePalindrome(string s) {\n return solve(s);\n }\n};\n``` | 1 | 0 | ['Greedy', 'C', 'C++'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.