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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-palindrome | Simple Java Solution in One Pass | simple-java-solution-in-one-pass-by-nosy-nils | Count duplicates in the pass, then check if we have an extra character to fix in the middle.\n\npublic int longestPalindrome(String s) {\n boolean[] map | nosydev | NORMAL | 2016-10-03T04:28:28.347000+00:00 | 2018-10-09T00:58:16.021143+00:00 | 7,776 | false | Count duplicates in the pass, then check if we have an extra character to fix in the middle.\n```\npublic int longestPalindrome(String s) {\n boolean[] map = new boolean[128];\n int len = 0;\n for (char c : s.toCharArray()) {\n map[c] = !map[c]; // flip on each occurrence, false when seen n*2 times\n if (!map[c]) len+=2;\n }\n if (len < s.length()) len++; // if more than len, atleast one single is present\n return len;\n }\n``` | 33 | 0 | [] | 5 |
longest-palindrome | [C++] solution | c-solution-by-naniko19-2cbo | \nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<int,int> mp;\n int res = 0;\n for(int i = 0; i < s.lengt | naniko19 | NORMAL | 2020-08-15T00:41:36.703462+00:00 | 2020-08-15T00:41:36.703496+00:00 | 4,273 | false | ```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<int,int> mp;\n int res = 0;\n for(int i = 0; i < s.length(); i++) {\n mp[s[i]]++;\n if(mp[s[i]]%2==0) {\n res += mp[s[i]];\n mp[s[i]] = 0;\n }\n }\n for(auto x: mp) {\n if(x.second==1) {\n res++;\n break;\n } \n }\n return res;\n }\n};\n``` | 27 | 1 | ['C', 'C++'] | 2 |
longest-palindrome | Python 3(Two-liner) - Faster than 99.26%, Memory usage less than 100% | python-3two-liner-faster-than-9926-memor-go1j | \nfrom collections import Counter\n\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n count = sum([(x//2) * 2 for x in Counter(s).value | mmbhatk | NORMAL | 2019-11-20T13:21:53.424289+00:00 | 2019-11-20T13:24:07.739178+00:00 | 3,991 | false | ```\nfrom collections import Counter\n\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n count = sum([(x//2) * 2 for x in Counter(s).values()])\n return count if count == len(s) else (count + 1)\n``` | 26 | 0 | ['Python', 'Python3'] | 4 |
longest-palindrome | Easy to understand accepted solution with explanation | easy-to-understand-accepted-solution-wit-81ce | First, characters are counted. Even occurring characters (v[i]%2 == 0) can always be used to build a palindrome. For every odd occurring character (v[i]%2 == 1) | vsmnv | NORMAL | 2016-10-02T05:52:07.096000+00:00 | 2018-10-12T02:08:05.557471+00:00 | 9,048 | false | First, characters are counted. Even occurring characters (v[i]%2 == 0) can always be used to build a palindrome. For every odd occurring character (v[i]%2 == 1), v[i]-1 characters can be used. Res is incremented if there is at least one character with odd occurrence number.\n```\n int longestPalindrome(string s) {\n vector<int> v(256,0);\n for(int i = 0; i < s.size(); ++i)\n ++v[s[i]];\n int res = 0;\n bool odd = false;\n for(int i = 0; i < 256; ++i)\n if(v[i]%2 == 0)\n res += v[i];\n else\n {\n res += v[i] - 1;\n odd = true;\n }\n if(odd)\n ++res;\n return res;\n }\n``` | 26 | 0 | [] | 7 |
longest-palindrome | Simple Java Solution | simple-java-solution-by-fabrizio3-f4ne | \npublic int longestPalindrome(String s) {\n\tif(s==null || s.length()==0) return 0;\n\tSet<Character> set = new HashSet<>();\n\tint count = 0;\n\tchar[] chars | fabrizio3 | NORMAL | 2016-10-03T06:10:49.358000+00:00 | 2016-10-03T06:10:49.358000+00:00 | 3,274 | false | ```\npublic int longestPalindrome(String s) {\n\tif(s==null || s.length()==0) return 0;\n\tSet<Character> set = new HashSet<>();\n\tint count = 0;\n\tchar[] chars = s.toCharArray();\n\tfor(char c: chars) {\n\t\tif(set.remove(c)) {\n\t\t\tcount++;\n\t\t} else {\n\t\t\tset.add(c);\n\t\t}\n\t}\n\treturn set.isEmpty() ? count*2 : count*2+1;\n}\n``` | 25 | 0 | ['Hash Table', 'Java'] | 4 |
longest-palindrome | Count Freq vs Even or Odd||0ms beats 100% | count-freq-vs-even-or-odd0ms-beats-100-b-wl88 | Intuition\n Describe your first thoughts on how to solve this problem. \nAt most one alphabet has an odd number of occurrencies in a palindrome string.\n\n2nd a | anwendeng | NORMAL | 2024-06-04T01:57:02.563293+00:00 | 2024-06-04T09:33:47.968624+00:00 | 6,205 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt most one alphabet has an odd number of occurrencies in a palindrome string.\n\n2nd approach uses bitset/long long & consider only the parity ( odd or even frequencies). C, C++ & Python are implemented.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use an array `freq[58]`, since \'A\'=65~\'z\'=122, there 122-65+1=122-64=58 alphabets\n2. Count `freq`\n3. Use a loop to count the length of longest palindrome string; if f in freq is even, `len+=f`, otherwise `len+=f-1`, & set `hasOdd=1`\n4. `len+hasOdd` is the answer\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n+58)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(58)$$\n# Code||0ms beats 100%\n```\nclass Solution {\npublic:\n static int longestPalindrome(string& s) {\n int freq[58]={0}; //\'A\'=65~\'z\'=122\n for(char c: s)\n freq[c-\'A\']++;\n int len=0;\n bool hasOdd=0;\n for(int f: freq){\n if ((f&1)==0) len+=f;\n else{\n len+=(f-1);\n hasOdd=1;\n }\n }\n return len+hasOdd;\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# 2nd approach using even or odd for freq arguement||C, C++0ms beats 100%\n```C++ []\nclass Solution {\npublic:\n static int longestPalindrome(string& s) {\n bitset<58> freq=0; //\'A\'=65~\'z\'=122\n for(char c: s)\n freq.flip(c-\'A\');\n int len=s.size();\n for(int i=0; i<58; i++){\n if (freq[i]) len--;//odd freq len-=1\n }\n return len+(freq.count()>=1);\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n```C []\n#pragma GCC optimize("O3", "unroll-loops")\nint longestPalindrome(char* s) {\n long long freq=0; \n int len=0;\n for(register int i=0; s[i]!=\'\\0\'; i++){\n freq^=(1LL<<(s[i]-\'A\'));\n len++;\n }\n bool hasOdd=0;\n for(register int i=0; i<58; i++){\n if ((freq>>i)&1){\n len--;\n hasOdd=1;\n }\n }\n return len+hasOdd;\n}\n```\n```Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n freq=0\n for c in s:\n freq^=(1<<(ord(c)-ord(\'A\')))\n L=len(s)\n hasOdd=0\n for i in range(58):\n if ((freq>>i)&1)==1: \n L-=1\n hasOdd=1\n return L+hasOdd\n```\n# 3rd C++ is a revised short form for the 2nd C++||0ms beats 100%\n```\nclass Solution {\npublic:\n static int longestPalindrome(string& s) {\n bitset<58> freq=0; //\'A\'=65~\'z\'=122\n for(char c: s)\n freq.flip(c-\'A\');\n int odd=freq.count();\n return s.size()-odd+(odd>=1);\n }\n};\n``` | 22 | 0 | ['Array', 'String', 'Bit Manipulation', 'C', 'C++', 'Python3'] | 7 |
longest-palindrome | C / C++ Solution O(n) time, O(1) space, 100.00% faster! | c-c-solution-on-time-o1-space-10000-fast-3x8v | C Solution\n\n\nint longestPalindrome(char * s)\n{\n int letters[52] = {0};\n bool is_odd = false;\n int longest_palindrome = 0;\n \n | debbiealter | NORMAL | 2020-08-14T08:52:17.124445+00:00 | 2020-08-14T09:23:30.393198+00:00 | 3,142 | false | # C Solution\n\n```\nint longestPalindrome(char * s)\n{\n int letters[52] = {0};\n bool is_odd = false;\n int longest_palindrome = 0;\n \n for(int i = 0; i < strlen(s); i++)\n {\n if(*(s + i) <= \'Z\')\n letters[*(s + i) -\'A\']++;\n \n else \n letters[*(s + i)-\'a\' + 26]++;\n }\n \n for(int i = 0; i < 52; i++)\n {\n longest_palindrome += letters[i] / 2;\n \n if(letters[i] % 2 == 1)\n is_odd = true;\n }\n\t\t\n return is_odd == true ? 2 * longest_palindrome + 1 : 2 * longest_palindrome;\n}\n```\n\n# C++ Solution\n\n```\nclass Solution \n{\npublic:\n int longestPalindrome(string s) \n {\n vector<int> letters(52, 0);\n bool is_odd = false;\n int longest_palindrome = 0;\n \n for(int i = 0; i < s.length(); i++)\n {\n if(s[i] <= \'Z\')\n letters[s[i] -\'A\' ]++;\n \n else \n letters[s[i] -\'a\' + 26]++;\n }\n \n for(int i = 0; i < 52; i++)\n {\n longest_palindrome += letters[i] / 2;\n \n if(letters[i] % 2 ==1)\n is_odd =true;\n }\n\t\t\n return is_odd == true ? 2 * longest_palindrome + 1 : 2 * longest_palindrome;\n }\n};\n``` | 21 | 1 | [] | 3 |
longest-palindrome | Python Solution with Explanation | python-solution-with-explanation-by-cody-ihsg | Assume character frequency = K\n\n1. If all the characters appears even times, then we just add up all the frequencies (K) and returns the result.\n\n\tEx. aabb | codyli520 | NORMAL | 2020-09-22T08:07:49.346757+00:00 | 2020-09-22T08:12:06.873718+00:00 | 2,096 | false | Assume character frequency = K\n\n1. If all the characters appears even times, then we just add up all the frequencies (K) and returns the result.\n\n\tEx. aabb -> abba\n\n2. If one or more characters appears odd times, we noted down that an odd frequency character had appeared, and just increment result `K-1` (since odd frequency reduced by 1 is even frequency, meaning we can use an odd frequency word even times). \n In the end, add 1 back to the overall sum, since in parlindrome, we can have one and only one odd frequency character (highest out of all odd frequency characters) and make the string longest parlindrome.\n\n\tEx. aabbcccppppp-> abppcpcppba\n\n\tHere `c` appears 3 times, `p` appears 5 times, we know we should always use the highest of all odd frequency character, and have the rest of the odd frequency words appear even times. In the example we ended up using `p` 5 times, but `c` 2 times, and it\'s the longnest parlindrome.\n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n from collections import Counter\n \n freq = Counter(s)\n \n odd = False\n res = 0\n \n for k,v in freq.items():\n if v % 2 == 0:\n res += v\n else:\n res += v-1\n odd = True\n \n if odd:\n res += 1\n \n return res\n``` | 20 | 0 | ['Python'] | 3 |
longest-palindrome | Simple Java beat 99.67% | simple-java-beat-9967-by-erintao-q2q0 | \npublic int longestPalindrome(String s) {\n int[] chars = new int[128];\n char[] t = s.toCharArray();\n for(char c:t){\n chars[ | ErinTao | NORMAL | 2017-06-06T05:00:25.221000+00:00 | 2018-09-18T03:10:52.464830+00:00 | 2,441 | false | ```\npublic int longestPalindrome(String s) {\n int[] chars = new int[128];\n char[] t = s.toCharArray();\n for(char c:t){\n chars[c]++;\n }\n int single = 0;\n for(int n:chars){\n if(n%2!=0){\n single++;\n }\n }\n return single>1?t.length-single+1:t.length;\n }\n``` | 19 | 0 | [] | 4 |
longest-palindrome | Simplest solution using HashSet | simplest-solution-using-hashset-by-abste-u1u2 | Intuition\nIn palindromes with even number of characters each of them must have a pair. We can use HashSet, then add and remove the same character, and at the t | abster2970 | NORMAL | 2023-01-30T18:29:29.319165+00:00 | 2023-01-30T18:42:45.083803+00:00 | 789 | false | # Intuition\nIn palindromes with even number of characters each of them must have a pair. We can use HashSet, then add and remove the same character, and at the time of removal that will be +2 to our overall length. \n\nIf in the end our set is not empty, no matter how many unique characters will be left over, it can be just "a" or "a, b, c", if we were building the palindrome, we could pick any of them and build the palindrome using that (there\'s no pair for each of them), that\'s why we\'re adding +1 in the end in that case.\n\n# Code\n```\npublic class Solution {\n public int LongestPalindrome(string s) {\n var set = new HashSet<char>();\n var maxLength = 0;\n\n foreach (var c in s)\n {\n if (set.Contains(c))\n {\n set.Remove(c);\n maxLength += 2;\n }\n else\n set.Add(c);\n }\n\n return set.Count > 0 ? maxLength + 1 : maxLength;\n }\n}\n``` | 18 | 0 | ['C#'] | 0 |
longest-palindrome | JAVA | 3 Approaches | Everything you'd need ✅ | java-3-approaches-everything-youd-need-b-xmxn | Please Upvote :D\n---\n##### 1. Using HashSet:\njava []\nclass Solution {\n public int longestPalindrome(String s) {\n Set<Character> set = new HashSe | sourin_bruh | NORMAL | 2022-10-17T12:40:50.929812+00:00 | 2023-01-08T06:35:27.493702+00:00 | 2,641 | false | # Please Upvote :D\n---\n##### 1. Using HashSet:\n``` java []\nclass Solution {\n public int longestPalindrome(String s) {\n Set<Character> set = new HashSet<>();\n int len = 0;\n for (char c : s.toCharArray()) {\n if (set.contains(c)) {\n len += 2;\n set.remove(c);\n }\n else set.add(c);\n }\n\n return set.size() > 0 ? len + 1 : len;\n }\n}\n\n// TC: O(n), SC: O(n)\n```\n---\n##### 2. Using HashMap:\n``` java []\nclass Solution {\n public int longestPalindrome(String s) {\n Map<Character, Integer> map = new HashMap<>();\n for (char c : s.toCharArray()) {\n map.put(c, map.getOrDefault(c, 0) + 1);\n }\n\n int len = 0;\n for (int i : map.values()) {\n len += (i % 2 == 0)? i : i - 1;\n }\n\n return len < s.length() ? len + 1 : len;\n }\n}\n\n// TC: O(n), SC: O(n)\n```\n---\n##### 3. Using Frequency array:\n``` java []\nclass Solution {\n public int longestPalindrome(String s) {\n int[] charCount = new int[128];\n for (char c : s.toCharArray()) {\n charCount[c]++;\n }\n\n int len = 0;\n for (int count : charCount) {\n len += 2 * (count / 2);\n }\n\n return len < s.length() ? len + 1 : len;\n }\n}\n\n// TC: O(n), SC: O(1)\n``` | 18 | 0 | ['Array', 'Hash Table', 'Java'] | 5 |
longest-palindrome | 🔥Most Easy Solution | [JAVA] | HashSet🤗 | most-easy-solution-java-hashset-by-dipes-j9us | 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 | dipesh_12 | NORMAL | 2023-01-11T09:00:59.985897+00:00 | 2023-01-11T09:00:59.985950+00:00 | 3,256 | 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 public int longestPalindrome(String s) {\n HashSet<Character>h=new HashSet<>();\n int len=0;\n for(char e:s.toCharArray()){\n if(h.contains(e)){\n len+=2;\n h.remove(e);\n }\n else{\n h.add(e);\n }\n }\n\n if(h.size()>0){\n return len+1;\n }\n return len;\n \n }\n}\n``` | 17 | 0 | ['Java'] | 4 |
longest-palindrome | Python || counter || explanation | python-counter-explanation-by-palashbajp-hh5z | Upvote if u like\n\n1. Count occurance of all characters\n2. If character occurs even times , add their count\n3. If character occurs odd times , add count-1 an | palashbajpai214 | NORMAL | 2022-07-01T04:33:48.497868+00:00 | 2022-07-01T04:33:48.497897+00:00 | 1,761 | false | ***Upvote if u like***\n\n1. Count occurance of all characters\n2. If character occurs even times , add their count\n3. If character occurs odd times , add count-1 and make oddFlag=1\n4. Palindrom can maximum have one odd occurance, at middle , so if oddFlag=1 return ans+1\n\n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n oddFlag=0\n \n count=collections.Counter(s)\n\n ans=0\n for k,v in count.items():\n if v%2==1:\n ans+=v-1\n oddFlag= 1\n else:\n ans+=v\n \n if oddFlag == 1:\n return ans+1\n return ans\n```\n | 17 | 0 | ['Python', 'Python3'] | 4 |
longest-palindrome | C++ So easy .. | c-so-easy-by-ravi0077-vj80 | We can include all even frequency characters in our palindrome.\nWe can include atmost one odd frequency characters to make a palindrome\n\nclass Solution {\npu | ravi0077 | NORMAL | 2020-08-14T07:04:54.632612+00:00 | 2020-08-19T07:14:14.313143+00:00 | 837 | false | We can include all even frequency characters in our palindrome.\nWe can include atmost one odd frequency characters to make a palindrome\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n \n vector<int>v(255,0);\n int c=0;\n for(int i=0;i<s.size();i++)\n {\n v[s[i]-65]++;\n if(v[s[i]-65]%2==0)\n c+=2;\n }\n if(s.size()>c)\n return c+1;\n else\n return c;\n }\n};\n``` | 17 | 17 | [] | 3 |
longest-palindrome | PYTHON - 35ms 99th percentile O(n) solution | python-35ms-99th-percentile-on-solution-4npvc | \n\nclass Solution(object):\n\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n ctmap = {}\n | moonstone1011 | NORMAL | 2016-10-28T17:29:17.346000+00:00 | 2018-10-08T09:04:23.078013+00:00 | 4,494 | false | \n\nclass Solution(object):\n\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n ctmap = {}\n for c in s:\n if c not in ctmap:\n ctmap[c] = 1\n else:\n ctmap[c] += 1\n\n ret = 0\n singleCharFound = 0\n for key in ctmap:\n if ctmap[key] % 2 == 0:\n ret += ctmap[key]\n else:\n ret += ctmap[key] - 1\n singleCharFound = 1\n \n return ret + singleCharFound | 17 | 0 | [] | 4 |
longest-palindrome | Simple Python O(N) solution using Counter | simple-python-on-solution-using-counter-nbzb3 | To solve this problem we need to identify the underlying structure of palindromes. A palindrome can either be made up of just characters which are present on bo | bloomh | NORMAL | 2022-10-02T18:36:54.224750+00:00 | 2022-10-02T18:36:54.224831+00:00 | 1,772 | false | To solve this problem we need to identify the underlying structure of palindromes. A palindrome can either be made up of just characters which are present on both sides of the middle, or it can be created from these symmetrical characters while having a character which sits directly in the middle. That is, in a palindrome such as ```abccba```, the center of the word is the empty space between the two ```c``` characters. In this case, there is an even number of ```a```, ```b```, and ```c```. However, in the word ```kayak```, there is an odd number of ```y``` since it is directly in the middle. This means that constructing the longest possible palindrome from a set of letters involves identifying all of the letters with even counts and then seeing if we have an exta letter we can stick directly into the middle. To do this, we will use the ```Counter``` datatype, which is a ```dictionary``` that (in our case) has letters as its ```keys``` and their counts as its ```values```. We can go through every value and check whether or not it is even. If it is, then we know we can add all the elements to our final palindrome. If it is not even, then we know we have an exta letter to stick into the middle of our final word. Additionally, if there are an odd number of elements but there are ```3```, ```5```, ```7```, etc. of them, then we could still use ```2```, ```4```, or ```6``` of them to add to either side of the array. This will always be one less than the total count of that element, since we aren\'t sure if we can use the extra character making it an odd number. This would be useful in an example like ```kayyyak```.\n\n**Solution Using Counter; Time: O(N), Space: O(N)**\n```\ndef longestPalindrome(self, s: str) -> int:\n\todd = 0 #whether or not we have any letters with an odd count\n\tans = 0 #answer\n\tfor count in collections.Counter(s).values():\n\t\tif count%2 == 0: #if we have an even amount of the letter\n\t\t\tans += count #we can use the letter\n\t\telse:\n\t\t\todd = 1 #we have found an od\n\t\t\tans += count-1 #we can use all but the 1 of the letter\n\treturn ans + odd #if there was an odd amt of a letter, we can add that letter to the middle of our palindrome\n```\n\n**Thanks for Reading!**\nIf this post has been helpful, please consider upvoting! Also, if I made any mistakes or there are other optimizations, methods I didn\'t consider, etc. please let me know! | 15 | 0 | ['Python'] | 1 |
longest-palindrome | C# HashSet solution | c-hashset-solution-by-newbiecoder1-gw7a | Time complexity: O(n)\nSpace complexity: O(1)\n\npublic class Solution {\n public int LongestPalindrome(string s) {\n \n if(s == null || s.Leng | newbiecoder1 | NORMAL | 2020-08-15T23:33:12.566079+00:00 | 2020-08-15T23:33:12.566124+00:00 | 611 | false | Time complexity: O(n)\nSpace complexity: O(1)\n```\npublic class Solution {\n public int LongestPalindrome(string s) {\n \n if(s == null || s.Length == 0)\n return 0;\n \n int len = 0;\n HashSet<char> set = new HashSet<char>();\n foreach(char c in s)\n {\n if(set.Contains(c))\n {\n len += 2;\n set.Remove(c);\n }\n else\n set.Add(c);\n }\n \n return set.Count > 0? len + 1 : len;\n }\n}\n``` | 14 | 0 | [] | 2 |
longest-palindrome | C : beats 100%, 4-lines, simple n short, no built-in Utils/Data Structures, O(1)S O(n)T | c-beats-100-4-lines-simple-n-short-no-bu-y0ht | NOTE : Whoever downvoted this, it is clear that you failed to understand the code here since it requires a seasoned C programmer to appreciate it. So, if you do | universalcoder12 | NORMAL | 2020-08-15T05:29:03.322154+00:00 | 2020-08-15T07:23:03.461789+00:00 | 494 | false | **NOTE :** Whoever downvoted this, it is clear that you ***failed*** to understand the code here since it requires a seasoned C programmer to appreciate it. So, if you ***don\'t*** understand, move on, but do \\****not***\\* just downvote to show your frustration. Period.\n\n```\nint longestPalindrome(char * s){\n int m[128] = { 0 }, a = 0, b = 0, c;\n while (*s && ++m[*s++]);\n for (int i = \'A\' - 1 ; ++i <= \'z\' ; m[i] && (a += m[i] - ((b |= c = m[i] & 0x1), c)));\n return a + b;\n}\n``` | 14 | 2 | ['C'] | 0 |
longest-palindrome | C# LINQ-based 2-liner | c-linq-based-2-liner-by-vlassov-insw | \n public int LongestPalindrome(string s) {\n var even = s.GroupBy(c => c).Select(g => g.Count() & ~1).Sum();\n return even < s.Length ? even + | vlassov | NORMAL | 2020-08-14T09:57:32.972105+00:00 | 2020-08-15T20:14:24.626772+00:00 | 370 | false | ```\n public int LongestPalindrome(string s) {\n var even = s.GroupBy(c => c).Select(g => g.Count() & ~1).Sum();\n return even < s.Length ? even + 1 : even;\n }\n``` | 14 | 0 | [] | 0 |
longest-palindrome | 🏆EASY SOLUTION || Simple Approach || C++ || PYTHON || JAVA🔥🚀💯 | easy-solution-simple-approach-c-python-j-c7h9 | \n\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1.Count Character Frequencie | nikhil73995 | NORMAL | 2024-06-04T00:17:59.259710+00:00 | 2024-06-04T06:23:35.875165+00:00 | 4,557 | false | \n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.Count Character Frequencies:\n\n ->Create a frequency map (HashMap or unordered_map) to count character frequencies.\n ->Iterate through each character in the string.\n ->Increment the count of each character in the frequency map.\n \n2.Calculate Palindrome Length:\n\n ->Initialize a variable to store the length of the longest palindrome.\n ->Iterate through each character frequency in the map.\n ->For characters with even frequency, add the entire frequency to the length.\n ->For characters with odd frequency, subtract 1 from the frequency and add it to the length. Set a flag if an odd frequency character is found.\n\n3.Adjust Length for Center Character:\n\n ->If an odd frequency character is found, increment the length by 1 to account for placing one odd character in the center of the palindrome.\n\n4.Return the Length of the Longest Palindrome:\n\n Return the final length as the result.\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int c = 0; // odd count\n unordered_map<char, int>m;\n for(auto ch : s) {\n m[ch]++;\n if (m[ch] & 1)\n c++;\n else \n c--;\n }\n if (c > 1)\n return s.length() - c + 1;\n return s.length();\n }\n};\n```\n```Python []\n def longestPalindrome(s):\n c = 0 # odd count\n freq = {}\n \n for ch in s:\n freq[ch] = freq.get(ch, 0) + 1\n if freq[ch] % 2 == 0:\n c -= 1\n else:\n c += 1\n \n if c > 1:\n return len(s) - c + 1\n return len(s)\n```\n```Java []\npublic class Main {\n public static int longestPalindrome(String s) {\n int oddCount = 0; // Count of characters with odd frequency\n HashMap<Character, Integer> frequencyMap = new HashMap<>();\n \n for (char ch : s.toCharArray()) {\n frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);\n if (frequencyMap.get(ch) % 2 == 0)\n oddCount--;\n else\n oddCount++;\n }\n \n if (oddCount > 1)\n return s.length() - oddCount + 1;\n return s.length();\n }\n```\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n\n``` | 13 | 1 | ['Hash Table', 'String', 'Greedy', 'C++', 'Java', 'Python3'] | 11 |
longest-palindrome | C++ solution using map, with explanations - O(n) time, O(1) space - faster than 96% | c-solution-using-map-with-explanations-o-ty2i | \nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int res = 0;\n unordered_map<char, int> map;\n for (int i=0; i<s.size( | yehudisk | NORMAL | 2020-08-14T08:34:09.298353+00:00 | 2020-08-14T08:35:14.001356+00:00 | 1,802 | false | ```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int res = 0;\n unordered_map<char, int> map;\n for (int i=0; i<s.size(); i++) // save in map the amount of each letter in s\n {\n map[s[i]]++;\n }\n bool flag = false;\n for (auto x : map)\n {\n res += x.second - (x.second % 2); // add 2 to res for each pair of the same letter\n if (x.second % 2) // allow one letter to be only once - for odd length palindrome\n flag = true;\n }\n if (flag)\n res++;\n return res;\n }\n};\n``` | 13 | 0 | ['C', 'C++'] | 2 |
longest-palindrome | [C++] Concise Solution Explained, 100% Time, ~99% Space | c-concise-solution-explained-100-time-99-wwnz | Okay, this is a nice, simple one: first of all we build our own usual frequency map, then we go through it, taking each frequency and rounding it down to the ne | ajna | NORMAL | 2019-11-22T17:46:08.340968+00:00 | 2020-08-14T07:49:49.269613+00:00 | 1,754 | false | Okay, this is a nice, simple one: first of all we build our own usual frequency map, then we go through it, taking each frequency and rounding it down to the next multiple of `2` before adding it to our accumulator variable `res`.\n\nNotice that I did it with bitwise operators just to show off, but `res += e.second >> 1 << 1;` is just equivalent to writing `res += e.second / 2 * 2;` in this case.\n\nOnce I am done, I finally check if the final sum is equal to the length of the original string or not, no need to check with a lot of characters. If it is not, it means I can just take one character to put in the middle to have an even longer palindrome.\n\nThe code I wrote 9 months ago:\n\n```cpp\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n // res created, frequency map created and populated\n int res = 0;\n std::unordered_map<char, int> f;\n for (auto c: s) f[c]++;\n for (auto e: f) {\n // I take the frequence and round it down to the next multiple of 2\n res += e.second >> 1 << 1;\n }\n // if i did not use all the available characters, then the max lenght is + 1\n return res + (res != s.size());\n }\n};\n```\n\nThe code as I updated it today, with only minor changes in order for it to work with a frequency array instead - much faster and efficient:\n\n```cpp\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n // res created, frequency array initialised and populated\n int res = 0;\n int f[52];\n for (auto &e: f) e = 0;\n for (auto c: s) f[c < \'a\' ? c - \'A\' : c - \'a\' + 26]++;\n for (auto e: f) {\n // I take the frequence and round it down to the next multiple of 2\n res += e >> 1 << 1;\n }\n // if i did not use all the available characters, then the max lenght is + 1\n return res + (res != s.size());\n }\n};\n``` | 13 | 2 | ['C', 'Counting', 'C++'] | 3 |
longest-palindrome | [Python] Hash Table faster than 99.88% | python-hash-table-faster-than-9988-by-is-bfl7 | Upvote If you like it \uFF1A\uFF09\n\n\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n count = {} # Hash Table \n ans = [] | isu10903027A | NORMAL | 2022-11-20T10:10:46.336007+00:00 | 2022-11-20T10:29:35.332112+00:00 | 3,773 | false | Upvote If you like it \uFF1A\uFF09\n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n count = {} # Hash Table \n ans = [] # every word\'s frequency \n odd= 0 # store an odd number\'s frequency \n for word in s:\n if word not in count:\n count[word] = 1\n else:\n count[word] += 1\n for times in count.values():\n ans.append(times)\n if times % 2 != 0:\n odd += 1 # calculate an odd number\'s frequency\n if odd != 0:\n return sum(ans) - odd + 1 \n elif odd == 0:\n return sum(ans) - odd\n```\n\n | 12 | 0 | ['Hash Table', 'Python', 'Python3'] | 1 |
longest-palindrome | 🔥Easiest Solution➡️All Language🔥🔥 | easiest-solutionall-language-by-sharma_2-r7c8 | Intuition\npython []\nclass Solution(object):\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n | Sharma_290 | NORMAL | 2024-06-04T00:16:43.867526+00:00 | 2024-06-04T00:16:43.867546+00:00 | 2,719 | false | # Intuition\n```python []\nclass Solution(object):\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n from collections import Counter\n \n counts = Counter(s)\n length = 0\n has_odd = False\n \n for count in counts.values():\n length += (count // 2) * 2\n if count % 2 == 1:\n has_odd = True\n \n if has_odd:\n length += 1\n \n return length\n\n```\n```Java []\nclass Solution {\n public int longestPalindrome(String s) {\n Map<Character, Integer> counts = new HashMap<>();\n \n for (char c : s.toCharArray()) {\n counts.put(c, counts.getOrDefault(c, 0) + 1);\n }\n \n int length = 0;\n boolean hasOdd = false;\n \n for (int count : counts.values()) {\n length += (count / 2) * 2;\n if (count % 2 == 1) {\n hasOdd = true;\n }\n }\n \n if (hasOdd) {\n length += 1;\n }\n \n return length;\n }\n}\n```\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1.Count Characters: Use a counter to count how many times each character appears in the string.\n\n2.Initialize Length and Odd Flag: Start with a length of 0 and a flag (has_odd) to check if there\'s any character with an odd count.\n\n3.Iterate Over Counts:\nFor each character count, add the largest even part of the count to the palindrome length.\nCheck if the count is odd. If it is, set the has_odd flag to True.\n\n4.Handle Odd Character: If there\'s any character with an odd count, add 1 to the length to place one odd character in the center.\n\n5.Return Result: Return the computed length of the longest possible palindrome.\n\n\n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char, int> counts;\n \n for (char c : s) {\n counts[c]++;\n }\n \n int length = 0;\n bool hasOdd = false;\n \n for (auto& pair : counts) {\n int count = pair.second;\n length += (count / 2) * 2;\n if (count % 2 == 1) {\n hasOdd = true;\n }\n }\n \n if (hasOdd) {\n length += 1;\n }\n \n return length;\n }\n};\n```\n\n\n | 11 | 0 | ['Python', 'C++', 'Java'] | 12 |
longest-palindrome | C++ 3 lines bit manipulations beats all | c-3-lines-bit-manipulations-beats-all-by-pe2w | The theory is very simple: we XOR each letter to its position, at the end, each 1 left stands for "there exists odd number of that letter".\ntotal number of let | alvin-777 | NORMAL | 2020-09-22T02:04:41.939851+00:00 | 2020-09-22T02:04:41.939894+00:00 | 514 | false | The theory is very simple: we XOR each letter to its position, at the end, each `1` left stands for "there exists odd number of that letter".\n`total number of letters` - `single letter(s) cannot be paired` + `if there is any single letter we can put ONE in the centre of the palindrome`\n\n```cpp\nint longestPalindrome(string s) {\n bitset<64> bits(0);\n for (char c : s) bits.flip(c - \'A\');\n return s.size() - bits.count() + bits.any();\n}\n``` | 11 | 1 | ['Bit Manipulation', 'C'] | 0 |
longest-palindrome | 5 lines C++ | 5-lines-c-by-vesion-2j7d | \nclass Solution {\npublic:\n int longestPalindrome(string s) {\n vector<int> m(256, 0); \n for (auto& c : s) m[c-'\\0']++;\n int | vesion | NORMAL | 2016-10-02T06:48:14.283000+00:00 | 2018-09-25T12:58:52.714836+00:00 | 6,280 | false | ```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n vector<int> m(256, 0); \n for (auto& c : s) m[c-'\\0']++;\n int result = 0;\n for (auto& i : m) result += i%2 ? (result%2 ? i-1 : i) : i;\n return result;\n }\n};\n``` | 11 | 0 | [] | 4 |
longest-palindrome | JAVASCRIPT✅EASY EXPLANATION✅[58ms]✅94.22%BEATS | javascripteasy-explanation58ms9422beats-66vqe | \n\n# Explanation\n1. The function takes a string s as input and initializes a variable answer to 0, which will be used to store the length of the longest palin | ikboljonme | NORMAL | 2023-03-31T00:22:30.060081+00:00 | 2023-03-31T00:22:30.060123+00:00 | 2,067 | false | \n\n# Explanation\n1. The function takes a string s as input and initializes a variable answer to 0, which will be used to store the length of the longest palindrome.\n\n2. An empty object hashTable is initialized, which will be used to store the frequency of each character in the input string.\n\n3. The function loops through each character char in the input string s.\n\n4. If the character char already exists in the hashTable, then its value is incremented by 1. If not, it is initialized to 0 and then incremented by 1.\n\n5. If the frequency of char is even, the answer variable is incremented by 2. This is because a palindrome can be formed by pairing two characters of the same type.\n\n6. After looping through all characters in the input string, the function checks if the length of the input string is greater than answer. If it is, then a single character can be added to the palindrome, so answer is incremented by 1.\n\n7. The final value of answer is returned as the length of the longest palindrome that can be formed using the characters in the input string.\n\n# Complexity\n- Time complexity:\nIt is O(n), where n is the length of the input string s. This is because the function loops through each character in the input string exactly once, and all other operations (object property access, comparison, addition, etc.) are constant time operations.\n\n- Space complexity:\nIt is also O(n), because the hashTable object will contain at most n entries (one for each character in the input string), and the size of each entry is constant. Therefore, the space used by the function will grow linearly with the size of the input string.\n\n# Code\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar longestPalindrome = function (s) {\n let answer = 0;\n let hashTable = {};\n for (let char of s) {\n hashTable[char] = (hashTable[char] || 0) + 1;\n if (hashTable[char] % 2 === 0) {\n answer += 2;\n }\n }\n return s.length > answer ? answer + 1 : answer;\n};\n\n``` | 10 | 0 | ['JavaScript'] | 0 |
longest-palindrome | JS || Single Loop || HashMap | js-single-loop-hashmap-by-shaanaliyev-wzwx | \n/**\n * @param {string} s\n * @return {number}\n */\nvar longestPalindrome = function(s) {\n let result = 0;\n const mem = new Set();\n for(let i=0; | 20250306.123qweasdcxz | NORMAL | 2023-03-09T21:00:19.740121+00:00 | 2023-03-09T21:00:19.740156+00:00 | 1,926 | false | ```\n/**\n * @param {string} s\n * @return {number}\n */\nvar longestPalindrome = function(s) {\n let result = 0;\n const mem = new Set();\n for(let i=0; i<s.length; i++) {\n if(mem.has(s[i])) {\n result+=2;\n mem.delete(s[i]);\n } else { \n mem.add(s[i]);\n }\n };\n return result + (mem.size > 0 ? 1 : 0);\n};\n``` | 10 | 0 | ['JavaScript'] | 4 |
longest-palindrome | 409: Solution with step by step explanation | 409-solution-with-step-by-step-explanati-1b99 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Initialize an empty dictionary freq_dict to store the frequency of eac | Marlen09 | NORMAL | 2023-03-06T04:06:43.242408+00:00 | 2023-03-06T04:06:43.242460+00:00 | 4,529 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize an empty dictionary freq_dict to store the frequency of each character in the string s.\n2. Iterate over each character char in the string s and add it to the dictionary freq_dict if it doesn\'t exist, or increment its frequency by 1 if it does.\n3. Initialize a variable length to 0, which will store the length of the longest palindrome.\n4. Iterate over each frequency freq in the values of the dictionary freq_dict and add up the length of all even-frequency characters by computing freq // 2 * 2 and adding it to the variable length.\n5. Check if there are any characters whose frequency is odd by using the any function on a generator expression that checks if the frequency is odd (freq % 2 == 1). If there are any such characters, add one of them to the length by incrementing length by 1.\n6. Return the variable length as the answer.\n\nThe algorithm works by observing that any palindrome can be constructed by pairing up characters with even frequencies, and adding a single character with an odd frequency if one exists. By iterating over the frequencies of each character and adding up the length of all even-frequency characters, and then adding one odd-frequency character (if any exist), we obtain the length of the longest possible palindrome that can be constructed from the characters in the input string.\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 longestPalindrome(self, s: str) -> int:\n # Initialize a dictionary to store the frequency of each character in the string\n freq_dict = {}\n for char in s:\n freq_dict[char] = freq_dict.get(char, 0) + 1\n \n # Initialize a variable \'length\' to 0, which will store the length of the longest palindrome\n length = 0\n \n # Iterate through the dictionary and add up the length of all even-frequency characters\n for freq in freq_dict.values():\n length += freq // 2 * 2\n \n # Check if there are any characters whose frequency is odd. If yes, add one of them to the length\n if any(freq % 2 == 1 for freq in freq_dict.values()):\n length += 1\n \n # Return the length as the answer\n return length\n\n``` | 10 | 0 | ['Hash Table', 'String', 'Greedy', 'Python', 'Python3'] | 1 |
longest-palindrome | C++ solution using hashmap ✅ | c-solution-using-hashmap-by-coding_menan-trge | Logic\nAll elements on either side of the palindrome have to be even if number so that thay can equally be distributed on each side. Other than the only element | coding_menance | NORMAL | 2022-10-13T11:56:10.767009+00:00 | 2022-10-31T11:15:05.621197+00:00 | 1,718 | false | # Logic\nAll elements on either side of the palindrome have to be even if number so that thay can equally be distributed on each side. Other than the only element which can have odd number of times repeated is the one at the middle in case of a string of odd length.\n\n*Example: ababcccbaba*\n\nOther than c all other elements are even in numbers/quantity. Only c is odd as it is centered [though even number of c\'s is also allowed]\n\n\n``` C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char, int> mp;\n for (char x:s) {\n mp[x]++;\n }\n int length=0, carry=0;\n for (auto x:mp) {\n if (x.second%2==1) {\n carry=1;\n length+=(x.second-1);\n } else length+=x.second;\n }\n return length+carry;\n }\n};\n```\n# My GitHub: https://github.com/crimsonKn1ght\n\n*If this code helps, please upvote it, it encourages me to write more solutions*\n | 10 | 0 | ['Hash Table', 'C++'] | 4 |
longest-palindrome | JAVA 100% Faster Solution | java-100-faster-solution-by-abhishekpate-q3jm | \nclass Solution {\n public int longestPalindrome(String s) {\n int[] freq = new int[256];\n for (char c : s.toCharArray()) freq[c]++;\n\n | abhishekpatel_ | NORMAL | 2021-07-21T03:57:44.288000+00:00 | 2021-07-21T03:57:44.288033+00:00 | 924 | false | ```\nclass Solution {\n public int longestPalindrome(String s) {\n int[] freq = new int[256];\n for (char c : s.toCharArray()) freq[c]++;\n\n int even = 0, odd = 0;\n for (int i = 0; i < 256; i++) {\n if (freq[i] % 2 == 0) even += freq[i];\n else {\n even += (freq[i] - 1);\n odd++;\n }\n\n }\n\n return odd == 0 ? even : even + 1;\n }\n}\n``` | 10 | 0 | ['Java'] | 1 |
longest-palindrome | Python | Easy | python-easy-by-khosiyat-hgnw | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n char_count = {}\n \n | Khosiyat | NORMAL | 2024-06-04T05:04:23.811173+00:00 | 2024-06-04T05:04:23.811201+00:00 | 1,351 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/longest-palindrome/submissions/1277058488/?envType=daily-question&envId=2024-06-04)\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n char_count = {}\n \n # Count frequency of each character\n for char in s:\n if char in char_count:\n char_count[char] += 1\n else:\n char_count[char] = 1\n \n length_of_palindrome = 0\n odd_count_found = False\n \n # Calculate the length of the longest palindrome\n for count in char_count.values():\n if count % 2 == 0:\n length_of_palindrome += count\n else:\n length_of_palindrome += count - 1\n odd_count_found = True\n \n # If there was at least one character with an odd count, we can place one in the middle\n if odd_count_found:\n length_of_palindrome += 1\n \n return length_of_palindrome\n\n```\n | 9 | 0 | ['Python3'] | 1 |
longest-palindrome | Python 3 || 3 lines, Counter || T/S: 99% / 98% | python-3-3-lines-counter-ts-99-98-by-spa-dauk | Here\'s the intuition:\n\nWe should use each same-character pair in s in building the longest palindrome. In addition, we can also use any one single character | Spaulding_ | NORMAL | 2024-06-04T00:50:09.225140+00:00 | 2024-06-04T21:03:05.158504+00:00 | 175 | false | Here\'s the intuition:\n\nWe should use each same-character pair in `s` in building the longest palindrome. In addition, we can also use any one single character left after the pairs are used.\n\nHere\'s the plan:\n- We apply `Counter` to `s` and use `values()` to determine the counts of the distinct characters.\n\n- We determine `pairCounts` the number of same-character pairs .\n- If there is a single character remaining, then `(pairCounts < len(s))` is true, and we use this fact to add 1 to the answer in this case. \n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n \n c = Counter(s).values()\n\n pairCounts = 2 * sum(x>>1 for x in c)\n\n return pairCounts + (pairCounts < len(s))\n```\n[https://leetcode.com/problems/longest-palindrome/submissions/1276889342/?envType=daily-question&envId=2024-06-04](https://leetcode.com/problems/longest-palindrome/submissions/1276889342/?envType=daily-question&envId=2024-06-04)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(s)`. | 9 | 0 | ['Python', 'Python3'] | 0 |
longest-palindrome | 📌📌Python3 || ⚡simple solution uwu | python3-simple-solution-uwu-by-maary-5pyb | \n\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n char_count = {}\n for char in s:\n char_count[char] = char_count | maary_ | NORMAL | 2023-03-01T23:12:09.860861+00:00 | 2023-03-06T23:21:57.221944+00:00 | 2,325 | false | \n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n char_count = {}\n for char in s:\n char_count[char] = char_count.get(char, 0) + 1\n \n odd_count = 0\n for count in char_count.values():\n if count % 2 == 1:\n odd_count += 1\n \n if odd_count <= 1:\n return len(s)\n else:\n return len(s) - odd_count + 1\n``` | 9 | 0 | ['Python3'] | 0 |
longest-palindrome | O(n) Time Complexity Java Solution with Algo | HashMap | on-time-complexity-java-solution-with-al-wlu1 | Algorithm\n Create a HashMap and add character if not present. If present then remove it from map.\n If there is no element left in map, then complete s can be | savan07 | NORMAL | 2022-05-13T09:41:53.380933+00:00 | 2022-05-13T09:41:53.380965+00:00 | 640 | false | **Algorithm**\n* Create a HashMap and add character if not present. If present then remove it from map.\n* If there is no element left in map, then complete s can be modified as a palindrome. So return length of s.\n* If there\'s some element left in map, then leaving one element which can be in centre of palindrome number, rest all cannot be taken for making palindrome. So return, length of s - length of map + 1\n\nTime Complexity: O(n)\n\n**Code**\n```\npublic int longestPalindrome(String s) {\n HashMap<Character, Integer> map = new HashMap();\n for(int i=0; i<s.length(); i++){\n char temp = s.charAt(i);\n if(map.get(temp) != null) map.remove(temp);\n else map.put(temp, i);\n }\n if(map.size() <= 1) return s.length();\n return s.length() - map.size() + 1;\n }\n```\n**Please upvote if it helped**\n*Feel free to ask any questions/query in comment section* | 9 | 0 | ['Java'] | 0 |
longest-palindrome | Kotlin - pure functional | kotlin-pure-functional-by-tucux-fo23 | \nclass Solution {\n fun longestPalindrome(s: String): Int {\n return minOf(\n s.length,\n 1 + s\n .groupingBy { | tucux | NORMAL | 2022-04-30T21:17:00.221439+00:00 | 2022-04-30T21:17:00.221473+00:00 | 486 | false | ```\nclass Solution {\n fun longestPalindrome(s: String): Int {\n return minOf(\n s.length,\n 1 + s\n .groupingBy { it }\n .eachCount()\n .map { (k, v) -> v / 2 * 2 }\n .sum()\n )\n }\n}\n``` | 9 | 0 | ['Kotlin'] | 0 |
longest-palindrome | C# | c-by-mhorskaya-m124 | \npublic int LongestPalindrome(string s) {\n\tvar result = s.GroupBy(c => c).Sum(g => g.Count() / 2 * 2);\n\treturn result == s.Length ? result : result + 1;\n} | mhorskaya | NORMAL | 2021-12-05T19:32:39.323254+00:00 | 2021-12-05T19:32:39.323282+00:00 | 590 | false | ```\npublic int LongestPalindrome(string s) {\n\tvar result = s.GroupBy(c => c).Sum(g => g.Count() / 2 * 2);\n\treturn result == s.Length ? result : result + 1;\n}\n``` | 9 | 0 | [] | 1 |
longest-palindrome | [Go] simple solution using map | go-simple-solution-using-map-by-nightybe-xiy5 | my solution using map.\n\ngo\nfunc longestPalindrome(s string) int {\n count := make(map[byte]int)\n for i:=0; i<len(s);i++{\n ch := s[i]\n | nightybear | NORMAL | 2020-08-15T02:31:17.952785+00:00 | 2020-08-15T02:31:17.952835+00:00 | 765 | false | my solution using map.\n\n```go\nfunc longestPalindrome(s string) int {\n count := make(map[byte]int)\n for i:=0; i<len(s);i++{\n ch := s[i]\n if _, ok := count[ch]; !ok {\n count[ch] = 1\n } else {\n count[ch] += 1\n }\n }\n \n ans := 0\n for _, val := range count {\n ans += val / 2 * 2\n if ans % 2 == 0 && val % 2 == 1 {\n ans += 1\n }\n }\n \n return ans\n}\n``` | 9 | 0 | ['Hash Table', 'Go'] | 3 |
longest-palindrome | [Java] Simple O(n) time solution with O(alphabetSize) space | java-simple-on-time-solution-with-oalpha-1j1r | \nclass Solution {\n public int longestPalindrome(String s) {\n int[] counts = new int[52];\n \n for (int i = 0; i < s.length(); i++) {\ | roka | NORMAL | 2020-08-14T07:14:02.506626+00:00 | 2020-08-14T07:24:15.033156+00:00 | 183 | false | ```\nclass Solution {\n public int longestPalindrome(String s) {\n int[] counts = new int[52];\n \n for (int i = 0; i < s.length(); i++) {\n char cur = s.charAt(i);\n int index = cur <= \'Z\' ? cur - \'A\' : cur - \'a\' + 26;\n counts[index]++;\n }\n\n int oddCount = 0;\n int answer = 0;\n \n for (int i = 0; i < 52; i++) {\n answer += counts[i] / 2 * 2;\n oddCount += counts[i] & 1;\n }\n \n return answer + Math.min(oddCount, 1);\n }\n}\n``` | 9 | 0 | [] | 1 |
longest-palindrome | C++ beats 100% | c-beats-100-by-deleted_user-99mn | C++ beats 100%\n\n\n\n# Code\n\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n vector<int>lower(26,0);\n vector<int>upper(26,0 | deleted_user | NORMAL | 2024-06-04T01:02:00.444297+00:00 | 2024-06-04T01:02:00.444316+00:00 | 606 | false | C++ beats 100%\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n vector<int>lower(26,0);\n vector<int>upper(26,0);\n for(int i=0;i<s.size();i++){\n if(s[i]>=\'a\'){\n lower[s[i]-\'a\']++;\n }\n else{\n upper[s[i]-\'A\']++;\n }\n\n }\n int c=0;\n int f=0;\n for(int i=0;i<26;i++){\n if(lower[i]%2==0){\n c += lower[i];\n }\n else{\n c += lower[i]-1;\n f=1;\n }\n if(upper[i]%2==0){\n c += upper[i];\n }\n else{\n c += upper[i]-1;\n f=1;\n }\n\n }\n return c+f;\n \n }\n};\n``` | 8 | 0 | ['C++'] | 0 |
longest-palindrome | 💯✅🔥Easy Java ,Python3 ,C++ Solution|| 3 ms ||≧◠‿◠≦✌ | easy-java-python3-c-solution-3-ms-_-by-s-tyew | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is to find the length of the longest palindromic substring in a given strin | suyalneeraj09 | NORMAL | 2024-06-04T00:28:23.903153+00:00 | 2024-06-04T00:28:52.020902+00:00 | 1,384 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find the length of the longest palindromic substring in a given string. A palindromic substring is a substring that reads the same backward as forward. For example, "aba" is a palindromic substring of "ababa".\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in the code is to count the frequency of each character in the string. Then, for each character, if its frequency is odd, it can be part of the longest palindromic substring only once. So, we subtract 1 from its frequency and add it to the total length of the longest palindromic substring. If the frequency is even, the character can be part of the longest palindromic substring as many times as its frequency. We add its frequency to the total length.\n# Complexity\n- Time complexity:O(n)\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\n```Java []\nclass Solution {\n public int longestPalindrome(String s) {\n int res = 0, val = 0;\n Map<Character, Integer> mp = new HashMap<>();\n for (char ch : s.toCharArray()) {\n mp.put(ch, mp.getOrDefault(ch, 0) + 1);\n }\n for (Map.Entry<Character, Integer> entry : mp.entrySet()) {\n if (entry.getValue() % 2 != 0) {\n res += entry.getValue() - 1;\n val = 1;\n } else {\n res += entry.getValue();\n }\n }\n return res + val;\n }\n}\n```\n```python3 []\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n res = 0\n val = 0\n mp = {}\n for ch in s:\n mp[ch] = mp.get(ch, 0) + 1\n for count in mp.values():\n if count % 2 != 0:\n res += count - 1\n val = 1\n else:\n res += count\n return res + val\n```\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int res = 0, val = 0;\n unordered_map<char, int> mp;\n for (char ch : s) {\n mp[ch]++;\n }\n for (auto entry : mp) {\n if (entry.second % 2 != 0) {\n res += entry.second - 1;\n val = 1;\n } else {\n res += entry.second;\n }\n }\n return res + val;\n }\n};\n```\n\n\n | 8 | 2 | ['String', 'Greedy', 'C++', 'Java', 'Python3'] | 5 |
longest-palindrome | Python simple kraken ninja covid version | python-simple-kraken-ninja-covid-version-nxzh | Intuition\n\nPalindromes are made up of pairs of matching characters, with an optional unmatched character in the center of the palindome (e.g. abba or abcba).\ | jmcmahon | NORMAL | 2023-01-16T01:00:53.523440+00:00 | 2023-01-16T01:00:53.523482+00:00 | 3,019 | false | # Intuition\n\nPalindromes are made up of pairs of matching characters, with an optional unmatched character in the center of the palindome (e.g. abba or abcba).\n\n# Approach\n\nUse a set to keep track of unmatched characters. If we encounter a character that is already in our set, we can add this pair to our palindrome (increasing the palindrome\'s length by +2) and remove the single from our set.\n\nIf we have any left over singles at the end, we can use one of them for the center of our palindrome to increase the palindrome length by 1.\n\n# Complexity\n- Time complexity: $O(n)$, since we iterate over each character in the string\n\n- Space complexity: $O(1)$, since the only extra storage we use is the counter for palindrome length and a set that is at most the size of our character set (ASCII, for example).\n\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n singles = set()\n length = 0\n\n for char in s:\n if char in singles:\n singles.remove(char)\n length += 2\n else:\n singles.add(char)\n \n if len(singles) > 0:\n length += 1\n \n return length\n\n``` | 8 | 0 | ['Python3'] | 3 |
longest-palindrome | Easy to Understand || Clean Solution || Fully Explained || O(n) || Java😊 | easy-to-understand-clean-solution-fully-yn96y | Request \uD83D\uDE0A:\n\nIf you find these solutions easy to understand and helpful, then\nPlease Upvote\uD83D\uDC4D\uD83D\uDC4D.\n\n\n# Code (Explained in comm | N7_BLACKHAT | NORMAL | 2022-12-29T06:13:13.669929+00:00 | 2022-12-29T06:13:13.669981+00:00 | 1,190 | false | # Request \uD83D\uDE0A:\n```\nIf you find these solutions easy to understand and helpful, then\nPlease Upvote\uD83D\uDC4D\uD83D\uDC4D.\n```\n\n# Code (Explained in comments) :\n```\nclass Solution \n{\n public int longestPalindrome(String s) \n {\n int count=0;\n HashSet<Character> data=new HashSet<Character>();\n for(int i=0;i<s.length();i++)\n {\n char c=s.charAt(i);\n if(data.contains(c))//if contains remove the charcter and increase count\n {\n count+=2;//2 for no duplicacy Eg-aa\n data.remove(c);\n }\n else//not contain add thr character\n {\n data.add(c);\n }\n }\n if(data.size()>0)\n count++;\n return count;\n }\n}\n``` | 8 | 0 | ['Hash Table', 'String', 'Greedy', 'Java'] | 0 |
longest-palindrome | JavaScript simple hashmap O(n) solution | javascript-simple-hashmap-on-solution-by-m3c2 | ```\nvar longestPalindrome = function(s) {\n var map = {};\n var result = 0;\n for(let i = 0; i < s.length; i++){\n if(map[s[i]] === undefined){ | jiakang | NORMAL | 2017-12-02T00:09:49.301000+00:00 | 2017-12-02T00:09:49.301000+00:00 | 1,025 | false | ```\nvar longestPalindrome = function(s) {\n var map = {};\n var result = 0;\n for(let i = 0; i < s.length; i++){\n if(map[s[i]] === undefined){\n map[s[i]] = 1;\n }\n else if(map[s[i]] === 1){\n map[s[i]] = undefined;\n result += 2;\n }\n }\n if(s.length > result){\n result += 1;\n }\n return result;\n}; | 8 | 0 | [] | 1 |
longest-palindrome | Java beats 100% | java-beats-100-by-deleted_user-fmmj | Java beats 100%\n\n\n\n# Code\n\nclass Solution {\n public int longestPalindrome(String s) {\n int[] array = new int[58];\n int count = 0,odd = | deleted_user | NORMAL | 2024-06-04T01:00:07.166596+00:00 | 2024-06-04T01:00:07.166614+00:00 | 1,097 | false | Java beats 100%\n\n\n\n# Code\n```\nclass Solution {\n public int longestPalindrome(String s) {\n int[] array = new int[58];\n int count = 0,odd = 0;\n\n for(char each : s.toCharArray()){\n array[each - \'A\']++;\n }\n\n for(int each : array){\n if(each % 2 == 0 && each != 0){\n count += each;\n }else if(each % 2 == 1 && each != 1){\n count += each -1; \n odd = 1;\n }else if(each == 1){\n odd = 1;\n }\n }\n\n return count + odd;\n }\n}\n``` | 7 | 0 | ['Java'] | 0 |
longest-palindrome | 2 ways | hashSet | Freq Arrays | JAVA | 2-ways-hashset-freq-arrays-java-by-rohin-l88k | 1 - using HashSet\n\t\t\t\n\t\t\tclass Solution {\n\t\t\t\tpublic int longestPalindrome(String s) {\n\t\t\t\t\tif(s==null || s.length()==0) return 0;\n\t\t\t\t\ | RohiniK98 | NORMAL | 2022-10-16T05:31:21.379738+00:00 | 2022-10-16T05:31:21.379786+00:00 | 1,086 | false | **1 - using HashSet**\n\t\t\t\n\t\t\tclass Solution {\n\t\t\t\tpublic int longestPalindrome(String s) {\n\t\t\t\t\tif(s==null || s.length()==0) return 0;\n\t\t\t\t\tHashSet<Character> hs = new HashSet<Character>();\n\t\t\t\t\tint count = 0;\n\t\t\t\t\tfor(int i=0; i<s.length(); i++){\n\t\t\t\t\t\tif(hs.contains(s.charAt(i))){\n\t\t\t\t\t\t\ths.remove(s.charAt(i));\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\ths.add(s.charAt(i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(!hs.isEmpty()) return count*2+1;\n\t\t\t\t\treturn count*2;\n\t\t\t } \n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\n**2 - using Frequency array**\n\t\t\t\n\t\t\tclass Solution {\n\t\t\t\tpublic int longestPalindrome(String s) {\n\t\t\t\t\tint[] freq = new int[128]; \n\t\t\t\t\tfor(char c : s.toCharArray()) {\n\t\t\t\t\t\t++freq[c];\n\t\t\t\t\t}\n\n\t\t\t\t\tint OddGroup = 0;\n\n\t\t\t\t\tfor(int i : freq) {\n\t\t\t\t\t\tOddGroup += i & 1;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn s.length() - OddGroup + (OddGroup > 0 ? 1 : 0); \n\t\t\t}\n\t\t} | 7 | 0 | ['Java'] | 0 |
longest-palindrome | Simple Java Solution Using HashMap & Value Count with Comments | simple-java-solution-using-hashmap-value-006j | \nclass Solution {\n public int longestPalindrome(String s) {\n HashMap<Character,Integer> map = new HashMap<>();\n int n=s.length();\n | imsanjaybisht | NORMAL | 2022-10-09T14:58:19.844480+00:00 | 2022-10-11T09:35:16.793193+00:00 | 1,644 | false | ```\nclass Solution {\n public int longestPalindrome(String s) {\n HashMap<Character,Integer> map = new HashMap<>();\n int n=s.length();\n for(int i=0;i<n;i++){\n map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);\n }\n\t\t//First of all put all the elements in the HashMap\n\t\t//Now there will be two things either the value will be divisible by 2 or not.\n int result=0;\n int odd=0;\n for(int i : map.values()){\n\t\t\t//If it is divisible then we will just add it to the result.\n if(i%2==0){\n result+=i;\n }\n\t\t\t//else we will sub 1 and add it to the answer so that we will always have even values\n\t\t\t/*\n\t\t\tFor example \n\t\t\taaa -> a->3\n\t\t\tif 3 -> we will need only a->2 so we will add value-1\n\t\t\t*/\n else{\n result+=i-1;\n odd=1;\n }\n }\n\t\t//why we are using odd?\n\t\t//This is beacause we can have a middle element and it is not neccassary that middle should be present in the string two time\n\t\t/*\n\t\tif aaab\n\t\tso we can have either aaa or aba either way works so just taking only one odd element\n\t\t*/\n return result+odd;\n }\n}\n``` | 7 | 0 | ['Java'] | 1 |
longest-palindrome | Greedy approach | O(n) | Explained | greedy-approach-on-explained-by-nadaralp-wmgp | Explanation\nLet\'s first understand what a palindrome is: a palindrome is a word that, if we read it from left to right, and from right to left, it will read t | nadaralp | NORMAL | 2022-06-16T12:36:49.669242+00:00 | 2022-06-16T12:41:54.407197+00:00 | 754 | false | # Explanation\nLet\'s first understand what a palindrome is: a palindrome is a word that, if we read it from left to right, and from right to left, it will read the same. Examples are "madam" and "level".\n\nThe problem says we should return the length of the palindrome that **can be built** from a given string `s`. We don\'t look for palindromes but build them.\n\nIf you look at the palindromes we\'ve written, an interesting property that pops up is that all the letters come up an `even` number of times, and only 1 letter will be `odd` if the string is odd, like "level". \n\n# Greedy approach\nWe can create a counter of the string. `key=occurrences`\nIf there are even occurrences for the given character, we simply add the number of occurrences to the result, as we can take all the letters. If there are odd occurrences for the given character, we add everything but 1 (take 4 out of 5). If we met atleast one odd occurrence, we should add +1 to our end result to maximize the possible palindrome that can be built.\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n s_counter = Counter(s)\n # We take all even, and biggest odd\n odd = 0\n result = 0\n for v in s_counter.values():\n if v % 2 == 0: result += v\n else:\n odd = 1\n result += (v-1) # We take all events and 1 left over\n \n return result + odd\n```\n\n# Complexity analysis\nTime - `O(n)` as we iterate over the string 2 times. 1 to create the counter, and another to count the occurrences.\nSpace - `O(n)/O(1)` the counter space. Technically since we are bound to only upper and lower English letters than it will be O(52). But for generic n input, the space complexity will be O(n). | 7 | 0 | ['Greedy', 'Python'] | 1 |
longest-palindrome | Simple Java solution with a set(NOT A MAP) and 10-lines code, easy understand | simple-java-solution-with-a-setnot-a-map-d4gq | Noticed the unit of constructing palindrome is pair of char. So we don\'t need to count Characters but just make a minus. \nRefer to this code, it\'s self-expla | paladintyrion | NORMAL | 2021-03-21T20:37:36.652632+00:00 | 2021-03-21T20:38:42.018156+00:00 | 415 | false | Noticed the unit of constructing palindrome is pair of char. So we don\'t need to count Characters but just make a minus. \nRefer to this code, it\'s self-explanatory.\n\n```\npublic int longestPalindrome(String s) {\n\tSet<Character> set = new HashSet<>();\n\tfor (char c : s.toCharArray()) {\n\t\tif (set.contains(c)) {\n\t\t\tset.remove(c);\n\t\t} else {\n\t\t\tset.add(c);\n\t\t}\n\t}\n\tint baseSize = s.length() - set.size();\n\tif (set.size() != 0) return baseSize + 1;\n\treturn baseSize;\n}\n``` | 7 | 0 | ['Java'] | 3 |
longest-palindrome | C++ | c-by-testrun260-5p55 | \nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char,int>freq;\n int res = 0;\n int oddCount = 0;\n | testrun260 | NORMAL | 2020-08-15T02:02:10.783754+00:00 | 2020-08-15T02:02:10.783786+00:00 | 393 | false | ```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char,int>freq;\n int res = 0;\n int oddCount = 0;\n for(int i = 0; i < s.length(); ++i){\n freq[s[i]]++;\n }\n /*\n two cases:\n if current counter is even, take all\n if current counter is odd, take even part, and set one as the mid part.\n */\n for(auto i : freq){\n if(i.second % 2 == 0){\n res += i.second;\n }else{\n res += i.second -1;\n oddCount = 1;\n }\n }\n \n return res + oddCount;\n }\n};\n``` | 7 | 0 | ['C'] | 0 |
longest-palindrome | 💯💯Easiest solution || 🔥🔥Without any Data Structure 🔥🔥|| Count Frequency || Easy to Understand | easiest-solution-without-any-data-struct-vxy0 | \n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\n public int longestPalindrome(String s) {\n boole | darshan_anghan | NORMAL | 2024-06-04T05:27:27.630326+00:00 | 2024-06-04T05:27:27.630345+00:00 | 808 | false | \n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int longestPalindrome(String s) {\n boolean[] arr = new boolean[123]; // a-z ASCII value is 65 to 90 && A-Z ASCII value is 97 to 122\n int i = 0;\n int ans = 0;\n while(i<s.length()){\n if(arr[(int)(s.charAt(i))]==false){ // odd time charactor occur & note down into the array\n arr[(int)(s.charAt(i))] = true; // note down into the array\n }else{\n arr[(int)(s.charAt(i))] = false; //even time charactor occur & ans+=2\n ans+=2;\n }\n i++;\n }\n\n //after while loop if any odd occur reamining then longest palindrome is ans+1\n for(i = 65; i<arr.length ; i++){\n if(arr[i])return ans+1;\n }\n\n //otherwise longest palindrome is ans\n return ans;\n }\n}\n``` | 6 | 0 | ['Java'] | 3 |
longest-palindrome | Easy and Simple Solution | Python | easy-and-simple-solution-python-by-kg-pr-k4z6 | Intuition\nTo solve the problem of finding the length of the longest palindrome that can be built from the given string, we need to understand the properties of | KG-Profile | NORMAL | 2024-06-04T04:46:05.679165+00:00 | 2024-06-04T04:46:05.679191+00:00 | 433 | false | # Intuition\nTo solve the problem of finding the length of the longest palindrome that can be built from the given string, we need to understand the properties of palindromes. A palindrome reads the same forward and backward. Here\u2019s the plan:\n\n1. **Count Character Frequencies:** First, we count the frequency of each character in the string.\n2. **Calculate Length of Palindrome:** A palindrome can use pairs of characters symmetrically. If a character appears an even number of times, all of those characters can be used. If it appears an odd number of times, one less than that number (which is even) can be used, and potentially one character can be placed in the center if we don\'t have a center yet.\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n counts = Counter(s)\n length = 0\n odd_found = False\n \n for count in counts.values():\n length += count if count % 2 == 0 else count - 1\n if count % 2 == 1:\n odd_found = True\n \n return length + 1 if odd_found else length\n``` | 6 | 0 | ['Python3'] | 1 |
longest-palindrome | Simple Intutive Solution with explanation | clean code [c++/go] | simple-intutive-solution-with-explanatio-pk5a | Intuition\n- We can count pairs to get our result. Count all pairs pairs and we can form string of length pairs*2 + 1\n- If summing up pairs does not equals to | anupsingh556 | NORMAL | 2024-06-04T01:55:14.382680+00:00 | 2024-06-04T01:55:14.382696+00:00 | 1,551 | false | # Intuition\n- We can count pairs to get our result. Count all pairs `pairs` and we can form string of length `pairs*2 + 1`\n- If summing up pairs does not equals to lenght of string it means there is atleast one character without pair we can use that in pallindrome as well\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- create a map to store count of each character. \n- Iterate through string and check if count of current is even if yes means we got our pair so we can increment pairs count\n- At the end check if `pairs*2` is equal to n if yes means there is no character with odd length so return n else we can also one odd character and return `pairs*2+1`\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n) for single pass over input string\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(52) for stroing all char count \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int n=s.size(),pairs=0;\n map<char, int> c;\n for(int i=0;i<n;i++) {\n c[s[i]]++;\n if(c[s[i]]%2==0)pairs++;\n }\n return pairs*2==n?n:pairs*2+1;\n }\n};\n```\n```Go []\nfunc longestPalindrome(s string) int {\n\tn := len(s)\n\tpairs := 0\n\tcount := map[rune]int{}\n\tfor _, ch := range s {\n\t\tcount[ch]++\n\t\tif count[ch]%2 == 0 {\n\t\t\tpairs++\n\t\t}\n\t}\n\tif pairs*2 == n {\n\t\treturn n\n\t}\n\treturn pairs*2 + 1\n}\n``` | 6 | 0 | ['C++', 'Go'] | 5 |
longest-palindrome | 2 Easy Interview Approaches ✅ || using HashMap🔥 || without Hasmap💯 || All Language Solution💯 | 2-easy-interview-approaches-using-hashma-li3d | \n\n# Approach - 1\n Describe your approach to solving the problem. \nUsing map - to store the frequency of the characters\n\n# Complexity\n- Time complexity: O | naman_malik | NORMAL | 2024-06-04T01:09:18.899807+00:00 | 2024-06-04T01:09:18.899824+00:00 | 2,124 | false | \n\n# Approach - 1\n<!-- Describe your approach to solving the problem. -->\nUsing map - to store the frequency of the characters\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 Map store atmost 52 unique char \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n map<char,int>m;\n int cnt=0,one=0;\n for(int i=0; i<s.size(); i++)\n {\n m[s[i]]++; //Stroe the frequency of characters\n }\n for(auto i:m)\n {\n if(i.second>1)\n cnt+=i.second/2*(2); //Adding even frequency\n\n if(i.second%2) //Adding odd frequency if exist\n one=1;\n }\n return cnt+one;\n }\n};\n```\n```java []\npublic class Solution {\n public int longestPalindrome(String s) {\n Map<Character, Integer> m = new HashMap<>();\n int cnt = 0;\n int one = 0;\n\n // Store the frequency of characters\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n m.put(c, m.getOrDefault(c, 0) + 1);\n }\n\n for (Map.Entry<Character, Integer> entry : m.entrySet()) {\n int freq = entry.getValue();\n if (freq > 1) // Adding even frequency\n cnt += (freq / 2) * 2;\n \n if (freq % 2 == 1) // Adding odd frequency if it exists\n one = 1; \n }\n \n return cnt + one;\n }\n}\n```\n```Python []\nclass Solution:\n def longestPalindrome(self, s):\n m = {}\n cnt = 0\n one = 0\n\n # Store the frequency of characters\n for ch in s:\n if ch in m:\n m[ch] += 1\n else:\n m[ch] = 1\n\n for freq in m.values():\n if freq > 1:\n cnt += (freq // 2) * 2 # Adding even frequency\n\n if freq % 2 == 1: # Adding odd frequency if it exists\n one = 1\n\n return cnt + one\n\n```\n```Python3 []\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n from collections import Counter\n\n m = Counter(s)\n cnt = 0\n one = 0\n\n for freq in m.values():\n if freq > 1:\n # Adding even frequency\n cnt += (freq // 2) * 2\n\n # Adding odd frequency if it exists\n if freq % 2 == 1:\n one = 1\n\n return cnt + one\n\n```\n\n\n# Approach - 2\n<!-- Describe your approach to solving the problem. -->\nUsing BitMasking\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 Map store atmost 52 unique char \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Python []\nimport collections\nclass Solution:\n def longestPalindrome(self, s):\n bits = 0\n\n result = 0\n for ch in s:\n bit = 1 << (ord(ch) - 65)\n if bits & bit:\n bits ^= bit\n result += 2\n else:\n bits |= bit\n\n if bits:\n result += 1\n\n return result\n\n```\n\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(const std::string &s) {\n std::vector<int> count(52, 0); // 26 for lowercase + 26 for uppercase\n int result = 0;\n\n for (char ch : s) {\n if (ch >= \'a\' && ch <= \'z\') {\n count[ch - \'a\']++;\n } else if (ch >= \'A\' && ch <= \'Z\') {\n count[ch - \'A\' + 26]++;\n }\n }\n\n bool oddFound = false;\n for (int cnt : count) {\n if (cnt % 2 == 0) {\n result += cnt;\n } else {\n result += cnt - 1;\n oddFound = true;\n }\n }\n if (oddFound) {\n result += 1;\n }\n\n return result;\n }\n};\n```\n```java []\npublic class Solution {\n public int longestPalindrome(String s) {\n long bits = 0; // Use 64-bit long to handle both uppercase and lowercase letters\n int result = 0;\n\n for (char ch : s.toCharArray()) {\n long bit;\n if (ch >= \'a\' && ch <= \'z\') {\n bit = 1L << (ch - \'a\'); // Lowercase letters\n } else if (ch >= \'A\' && ch <= \'Z\') {\n bit = 1L << (ch - \'A\' + 26); // Uppercase letters, offset by 26\n } else {\n continue; // Ignore other characters\n }\n\n if ((bits & bit) != 0) {\n bits ^= bit;\n result += 2;\n } else {\n bits |= bit;\n }\n }\n\n if (bits != 0) {\n result += 1;\n }\n\n return result;\n }\n}\n\n```\n\n\n | 6 | 1 | ['Hash Table', 'String', 'Ordered Map', 'Swift', 'Python', 'C++', 'Java'] | 3 |
longest-palindrome | ⚡️Easy Python 3 | Greedy Solution ⚡️O(n) | beats 85% | 64ms 🔥 | easy-python-3-greedy-solution-on-beats-8-3439 | Intuition\n\nPalindrome is - a word that reads the same when read from left to right and from right to left. It explains that the task is to determine the lengt | nicolalino | NORMAL | 2023-05-03T15:52:31.587152+00:00 | 2023-05-03T15:52:31.587199+00:00 | 2,066 | false | # Intuition\n\nPalindrome is - a word that reads the same when read from **left** to **right** and from right to left. It explains that the task is to determine the length of a palindrome that can be formed using a given string. The approach taken is to build the palindrome rather than searching for it. The passage notes that in all the palindromes given as examples, each letter appears an even number of times except for one letter, which appears an odd number of times in cases where the string length is odd.\n\n# Greedy Approach\nWe can create a counter of the string. key=occurrences If there are even occurrences for the given character, we simply add the number of occurrences to the result, as we can take all the letters. If there are odd occurrences for the given character, we add everything but 1 (take 4 out of 5). If we met atleast one odd occurrence, we should add +1 to our end result to maximize the possible palindrome that can be built.\n\n# Complexity\n- Time complexity:\nTime - O(n) as we iterate over the string 2 times. 1 to create the counter, and another to count the occurrences.\n\n\n- Space complexity:\nO(n)/O(1) the counter space. Technically since we are bound to only upper and lower English letters than it will be O(52). But for generic n input, the space complexity will be O(n).\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n s_counter = Counter(s)\n # We take all even, and biggest odd\n odd = 0\n result = 0\n for v in s_counter.values():\n if v % 2 == 0: result += v\n else:\n odd = 1\n result += (v-1) # We take all events and 1 left over\n \n return result + odd\n\n\n\n\n\n\n\n\n\n\n``` | 6 | 0 | ['Greedy', 'Python', 'Python3'] | 0 |
longest-palindrome | C++ || 2 DIFFIERENT APPROACHS || ARRAY AND HASHMAP || EASY | c-2-diffierent-approachs-array-and-hashm-7jno | --->Here\'s a step-by-step explanation of the code:\n\n1-The program starts by defining a function longestPalindrome that takes a string s as input and return | Ayush00001 | NORMAL | 2023-04-04T16:51:00.084285+00:00 | 2023-04-14T06:13:30.109868+00:00 | 2,015 | false | --->Here\'s a step-by-step explanation of the code:\n\n1-The program starts by defining a function longestPalindrome that takes a string s as input and returns an integer.\n\n2-It first checks if the length of the string is 1. If it is, then it returns 1 because a palindrome of length 1 can be formed using a single character.\n\n3-It declares a variable count to keep track of the number of characters with an odd count.\n\n4-It then declares an integer array arr of size 256 (which is the number of ASCII characters) and initializes all the elements to 0.\n\n5-It then loops through each character in the input string s and increments the corresponding element in the arr array.\n\n6-After counting the occurrence of each character, it loops through each element in the arr array and checks if the count of that character is odd. If it is, then it increments the count variable.\n\n7-After counting the number of characters with an odd count, it checks if the count is greater than 1. If it is, then it subtracts the odd count from the length of the string and adds 1 to get the length of the longest palindrome that can be formed. Otherwise, it returns the length of the string as it is.\n\n8-The program then returns the length of the longest palindrome that can be formed.\n\nOverall, the program is an efficient way to find the length of the longest palindrome that can be formed using the characters of a given string. It has a time complexity of O(n) and a space complexity of O(1), where n is the length of the input string.\n\nUPVOTE IF YOU FIND IT INTERESTING \nJAI SHREE RAM\n\n\n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n //CREATE A ARRAY OF SIZE ALL ASCII VALUES AND ADD THE OCCURANCE OF ALL THE CHARACTER THIER \n if(s.length()==1){\n return 1;\n }\n int count=0;\n \n int arr[256]={0};\n for(int i=0;i<s.length();i++){\n //STORE THE VALUES AND THIER COUNT\n arr[s[i]]++;\n }\n for(int i=0;i<256;i++){\n if(arr[i]%2==1){\n //COUNT THE NUMBER OF ODD ALPHABHET\n count++;\n }\n }\n if(count>1){\n //IF ODD COUNT IF GREATER THAN 1 THAT MEAN IT HAS MORE THAN 1 CHARACTER WITH ODD COUNT SO WE CAN YOU ONLY ONE SO WILL SUBTRACT THE ODD COUNT AND ADD 1 BECAUSE WE CAN USE ON ODD ALPHABET...\n return s.length()-count+1;\n }\n return s.length();\n\n//____________________________________________________________________________\n//________________________________________________________________________________________________________________________________________\n //HASHMAP APPROACH SIMPLE ADD VALUES AND THEIR RESPECTIVE COUNT IN HASH MAP AND THAN COUNT THE NUMBER OF ODD COUNT\n int oddCount = 0;\n unordered_map<char, int> ump;\n for(char ch : s) {\n ump[ch]++;\n }\n for(int i=0;i<ump.size();i++){\n if(ump[i]%2==1){\n oddCount++;\n }\n \n }\n cout<<oddCount<<" "<<endl;\n if (oddCount > 1)\n return s.length() - oddCount + 1;\n return s.length();\n \n }\n};\n``` | 6 | 0 | ['C++'] | 3 |
longest-palindrome | ✅ Everything explained using comment | Easy Approach | everything-explained-using-comment-easy-63nc6 | \n// C++ Solution:\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n \n unordered_map<int,int> mp;\n int res = 0;\n | Sayakmondal | NORMAL | 2022-08-16T17:50:50.386797+00:00 | 2022-08-18T05:07:38.310063+00:00 | 569 | false | ```\n// C++ Solution:\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n \n unordered_map<int,int> mp;\n int res = 0;\n for(int i = 0; i < s.length(); i++) {\n mp[s[i]]++;\n // if a particular character occurs in even we can definitely take it and place both side of middle.\n if(mp[s[i]]%2==0) {\n res += mp[s[i]];\n mp[s[i]] = 0;\n }\n }\n for(auto x: mp) {\n // if one or more(take only one of them) character occurs only once we can place it at the middle of the palindrome string\n if(x.second==1) {\n res++;\n break;\n } \n }\n return res;\n }\n};\n\n/* \n\tif(you like)\n\t\tplease upvote;\n*/\n``` | 6 | 0 | ['C', 'C++'] | 1 |
longest-palindrome | Javascript, oddCount | javascript-oddcount-by-fbecker11-hqbz | \nvar longestPalindrome = function(s) {\n const map = new Map()\n for(const c of s){\n map.set(c, (map.get(c) || 0) + 1)\n }\n let count = 0\n let oddCo | fbecker11 | NORMAL | 2022-06-24T14:09:42.540410+00:00 | 2022-06-24T14:09:42.540448+00:00 | 768 | false | ```\nvar longestPalindrome = function(s) {\n const map = new Map()\n for(const c of s){\n map.set(c, (map.get(c) || 0) + 1)\n }\n let count = 0\n let oddCount = 0\n for(const [k, v] of map){\n if(v % 2 === 0){\n count+=v\n }else{\n count+=v\n oddCount++\n }\n }\n\n return oddCount ? count - oddCount + 1 : count\n};\n``` | 6 | 0 | ['JavaScript'] | 2 |
longest-palindrome | 0 ms, faster than 100.00% of C++ online submissions | 0-ms-faster-than-10000-of-c-online-submi-va07 | \nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int len=1;\n unordered_map<char,int>mp;\n for(auto c:s){\n | Troy_01 | NORMAL | 2021-12-22T13:26:19.536747+00:00 | 2021-12-22T13:26:19.536784+00:00 | 553 | false | ```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int len=1;\n unordered_map<char,int>mp;\n for(auto c:s){\n mp[c]++;\n }\n for(auto x:mp){\n if(x.second>=2){\n if(x.second%2==0)len+=x.second;\n else len+=x.second-1;\n }\n }\n if(len>s.size())return len-1;\n return len;\n }\n};\n``` | 6 | 0 | ['C'] | 0 |
longest-palindrome | C++ straight forward solution faster than 100% | c-straight-forward-solution-faster-than-q1bxi | Logic:\nAny character with even frequency could be included in palindrome.\ni.e. AAaaBBbb --> AaBbbBaA\nIn addition, character with odd frequency could be inc | AyushMistry | NORMAL | 2021-11-05T18:23:21.789086+00:00 | 2021-11-05T18:25:22.818253+00:00 | 249 | false | **Logic:**\nAny character with even frequency could be included in palindrome.\ni.e. AAaaBBbb --> AaBbbBaA\nIn addition, character with odd frequency could be included by ignoring it\'s one apperance and one char with odd frequency. \ni.e. AAaaBBbbcccd --> AaBbcccbBaA (OR) AaBbcdcbBaA\n\n**Approach:**\nCalculate freqeuncy of each character.\nFor even frequency, add it to the total.\nFor odd frequency, ignore it\'s one apperance, now this is also char with even frequency, add freq-1 to the total.\nWe can have one char with odd frequncy so add 1 to the total. (If char with odd frequency are there.)\n\n**Code:**\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int freq[52]={0},total=0,flag=0;\n for(int i=0;i<s.length();i++){\n if(s[i]>=\'a\')\n freq[s[i]-\'a\'+26]++;\n else\n freq[s[i]-\'A\']++;\n }\n for(int i=0;i<52;i++){\n if(freq[i]%2){\n total+=freq[i]-1;\n flag=1;\n }\n else\n total+=freq[i];\n }\n if(flag)\n total+=1;\n return total;\n }\n}; \n```\n\n | 6 | 0 | [] | 3 |
longest-palindrome | Python O(n) time using hashmap with explanation | python-on-time-using-hashmap-with-explan-neut | Essentially we want to counting pairs, plus one if there is another non-pair character aka\nlongestPlindrome = 2*numPairs + 1 if 2*numPairs < len(s) (the extra | algorithm_cat | NORMAL | 2020-08-15T06:40:20.560556+00:00 | 2020-08-15T06:40:20.560603+00:00 | 192 | false | Essentially we want to counting pairs, plus one if there is another non-pair character aka\n`longestPlindrome = 2*numPairs + 1 if 2*numPairs < len(s)` (the extra 1 is because a single character can go in the middle)\nWe have two options:\n1. sort with potentially no extra space but `O(nlogn)` time\n2. use a hashmap -> a bit extra space but` O(n)` time\n\nI choose option 2 because at maximum the hashmap size is bounded at `O(56)` due to the string only containing lower and upper case letters(26*2), so essentially it is `O(1)` extra space. On large inputs we would save a lot of time with option 2 with no extra cost in space.\n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n pairsCount = 0\n charMap = Counter(s)\n n = len(s)\n for c in charMap:\n pairsCount += charMap[c] // 2\n palindromeLength = pairsCount * 2\n if palindromeLength < n:\n palindromeLength += 1\n return palindromeLength\n``` | 6 | 0 | [] | 0 |
longest-palindrome | simple python solution with hash table | simple-python-solution-with-hash-table-b-ru5a | \nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n s_dict, l, flag = dict(), len(s), False\n for c in s:\n s_dict[c] | dobuzi | NORMAL | 2020-08-15T01:41:27.502230+00:00 | 2020-08-15T01:41:27.502260+00:00 | 129 | false | ```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n s_dict, l, flag = dict(), len(s), False\n for c in s:\n s_dict[c] = s_dict.get(c, 0) + 1\n for v in s_dict.values():\n if v%2 == 1:\n l -= 1\n flag = True\n return l + 1 if flag else l\n``` | 6 | 0 | [] | 0 |
longest-palindrome | [java] Simple solution, faster than 100% | java-simple-solution-faster-than-100-by-qfu1a | \nclass Solution {\n public int longestPalindrome(String s) {\n boolean[] seen = new boolean[58];\n int len = 0; \n int singles = 0; | deriso | NORMAL | 2020-08-15T00:26:07.197371+00:00 | 2020-08-15T00:26:07.197402+00:00 | 116 | false | ```\nclass Solution {\n public int longestPalindrome(String s) {\n boolean[] seen = new boolean[58];\n int len = 0; \n int singles = 0;\n \n for (char c : s.toCharArray()) {\n int index = c - \'A\';\n if (seen[index]) {\n seen[index] = false;\n len += 2;\n singles--;\n } else {\n seen[index] = true;\n singles++;\n }\n }\n \n return len + (singles > 0 ? 1 : 0);\n }\n}\n``` | 6 | 0 | [] | 0 |
longest-palindrome | Simple fast Java solution | simple-fast-java-solution-by-jono_m-tmav | \n public int longestPalindrome(String s) {\n int [] chars = new int[128];\n int len = s.length();\n \tfor(char ch : s.toCharArray()) {\n | jono_m | NORMAL | 2020-08-14T09:49:21.358579+00:00 | 2020-08-20T11:34:34.317663+00:00 | 602 | false | ```\n public int longestPalindrome(String s) {\n int [] chars = new int[128];\n int len = s.length();\n \tfor(char ch : s.toCharArray()) {\n \t\tchars[ch - \'A\'] ^= ch;\n \t\tlen = len + (chars[ch - \'A\'] == 0 ? 1 : -1);\n \t}\n \treturn len == s.length() ? len : len + 1;\n }\n``` | 6 | 0 | ['Java'] | 1 |
longest-palindrome | 1ms Java Solution with Test Case | 1ms-java-solution-with-test-case-by-shaw-zyl5 | \nclass Solution {\n // ""\n // "AaAa"\n // "aaa"\n // "aaaa"\n // "AAA"\n // "AAAA"\n // "AacAaa"\n // Time: O(n)\n // Space: O(1)\n | shawnngo | NORMAL | 2019-10-01T23:44:44.919397+00:00 | 2019-10-01T23:44:44.919463+00:00 | 271 | false | ```\nclass Solution {\n // ""\n // "AaAa"\n // "aaa"\n // "aaaa"\n // "AAA"\n // "AAAA"\n // "AacAaa"\n // Time: O(n)\n // Space: O(1)\n public int longestPalindrome(String s) {\n if (s == null) return 0;\n \n int[] count = new int[128];\n for (char c : s.toCharArray()) {\n count[c]++;\n }\n \n int res = 0;\n for (int num : count) {\n res += (num/2) * 2;\n }\n \n return res == s.length() ? res : res + 1;\n }\n}\n``` | 6 | 0 | [] | 0 |
longest-palindrome | 100% Beats Java Solution , Bitwise Approach to Maximize Palindrome Length in Linear Time🔥. | 100-beats-java-solution-bitwise-approach-uur3 | Intuition\nUse a bitmask to track character frequencies. Each character toggles a specific bit; 1 means odd frequency, 0 means even. Count the 1s to get the odd | deepu_01 | NORMAL | 2024-11-06T09:47:56.697344+00:00 | 2024-11-06T12:52:09.593578+00:00 | 231 | false | # Intuition\nUse a bitmask to **track character frequencies**. Each character toggles a specific bit; 1 means odd frequency, 0 means even. Count the 1s to get the odd-frequency characters. Max palindrome length is **n - (odd_count - 1).**\n\n# Complexity\n- Time complexity: **O(n)**\n\n- Space complexity: **O(1)**\n\n# Code\n```java []\nclass Solution {\n public int longestPalindrome(String str) {\n long bit=0L;\n int n=str.length();\n for(int i=0;i<n;i++) bit^=(1L<<(str.charAt(i)-\'A\')); \n bit=Long.bitCount(bit);\n return n-(int)(bit==0?0:bit-1);\n }\n}\n``` | 5 | 0 | ['Bit Manipulation', 'Bitmask', 'Java'] | 1 |
longest-palindrome | C++ easy and simple solution without using Hashmap and beats 100% | c-easy-and-simple-solution-without-using-yyrk | Intuition\nkeep record of occurances of each character\n# Approach\n1. Every even lenght palindrome have even no of occurances of characters so for even occuran | sahil_singh10 | NORMAL | 2024-06-04T15:49:38.725561+00:00 | 2024-06-04T15:49:38.725594+00:00 | 230 | false | # Intuition\nkeep record of occurances of each character\n# Approach\n1. Every even lenght palindrome have even no of occurances of characters so for even occurance we add occurance to the lenght as it is.\n2. Every odd length palindrome should have only one odd occurance so if the lenght of string is more than usual then their might be a case where odd occurance occurs more than once.\n3. so for that case we count every odd occurance by reducing 1 from it which makes it even and palindrome.\n\n\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int x,i,sum=0;\n x = s.size();\n if(x==1) return 1;\n vector<int> freq(123,0);\n bool hasodd = false;\n\n for(i=0;i<x;i++){ // for keeping occurances of each character in the string\n freq[s[i]]++;\n }\n\n for(i=65;i<123;i++){ //ascii value of A=65\n if(freq[i]>0 && freq[i]%2==0) sum+=freq[i];\n\n else if(freq[i]%2 != 0){\n sum+= freq[i] - 1;\n hasodd = true;\n }\n if(i==90) i=96;\n }\n if(hasodd) return sum + 1;\n return sum;\n }\n};\n``` | 5 | 0 | ['String', 'C++'] | 0 |
longest-palindrome | ✅ One Line Solution | one-line-solution-by-mikposp-niam | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: O(n). Space complexi | MikPosp | NORMAL | 2024-06-04T08:04:40.855200+00:00 | 2024-06-04T08:13:52.984578+00:00 | 1,068 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n return min(sum(v&~1 for v in Counter(s).values())+1,len(s))\n```\nSeen [here](https://leetcode.com/problems/longest-palindrome/solutions/89587/what-are-the-odds-python-c/comments/94209)\n\n# Code #2\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n return sum(reduce(lambda q,v:(q[0]+v&~1,q[1]|v&1),Counter(s).values(),(0,0)))\n```\n\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better) | 5 | 0 | ['Hash Table', 'String', 'Python', 'Python3'] | 0 |
longest-palindrome | Fast and Easy solution by using frequency of characters concept | HashMap |C++ and Java solution 💯✅ | fast-and-easy-solution-by-using-frequenc-2chh | Intuition \uD83E\uDDE0\n Describe your first thoughts on how to solve this problem. \nWe need to have store frequency of each character to check whether it is o | purnimakesarwani47 | NORMAL | 2024-06-04T05:22:18.228582+00:00 | 2024-06-04T05:22:18.228640+00:00 | 709 | false | # Intuition \uD83E\uDDE0\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to have store frequency of each character to check whether it is odd or even.\n\n---\n\n\n# Approach \uD83E\uDE9C\n<!-- Describe your approach to solving the problem. -->\n1. Make a map which will store the frequency of each character of string s.\n2. Initialize variables for counting longest length of palindrome`(len = 0)` and second for checking if odd freq has encountered`(flag = false)`.\n3. Now put characters of string s in hm along with its freq.\nSo `key of hm is char of s` and `value of hm is its freq`.\n\n```java []\nHashMap<Character, Integer> hm = new HashMap<>();\nint len = 0;\nboolean flag = false;\n\nfor (char ch : s.toCharArray()) {\n hm.put(ch, hm.getOrDefault(ch, 0) + 1);\n}\n```\n```C++ []\nmap<char, int> hm;\nint len = 0;\nbool flag = false;\n\nfor (char ch : s) {\n hm[ch]++;\n}\n```\n4. Now check the values of hm is odd or not.\n5. If freq is `even` then simply add its `freq` in len.\n6. But if the freq is `odd` then add `(freq - 1)` in its len and \nmake `flag = true`.\nFor example String s = "cccddd"\nhm will store` key = \'c\', val = 3 & key = \'d\', val = 3`\nBoth the frequencies are odd therefore len in the loop would be equal to `4`. But longest palidrome could be of length `5` therefore we will return `len + 1 when flag = true`. \n\n```java []\nfor (int freq : hm.values()) {\n if (freq % 2 == 0) { // even\n len += freq;\n } else { //odd \n len += freq - 1;\n flag = true;\n }\n}\n\nreturn flag == true ? len + 1 : len;\n```\n```C++ []\nfor (auto& el : hm) {\n int freq = el.second;\n if (freq % 2 == 0) {\n len += freq;\n } else {\n len += freq - 1;\n flag = true;\n }\n}\n\nreturn flag == true ? len + 1 : len;\n```\n\n7. We will not simply add 1 to len if freq is odd since it will fail cases \nfor `freq > 1`. \nTherefore we are adding first (freq - 1) then at last adding +1 if odd has been encountered otherwise we will return len.\n\n---\n\n\n# Complexity \uD83D\uDC69\u200D\uD83D\uDCBB\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---\n\n\n\n# Code \uD83D\uDE0A\uD83D\uDCBB\n```java []\nclass Solution {\n public int longestPalindrome(String s) {\n HashMap<Character, Integer> hm = new HashMap<>();\n int len = 0;\n boolean flag = false;\n\n for (char ch : s.toCharArray()) {\n hm.put(ch, hm.getOrDefault(ch, 0) + 1);\n }\n\n for (int freq : hm.values()) {\n if (freq % 2 == 0) { \n len += freq;\n } else {\n len += freq - 1;\n flag = true;\n }\n }\n\n return flag == true ? len + 1 : len;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n map<char, int> hm;\n int len = 0;\n bool flag = false;\n\n for (char ch : s) {\n hm[ch]++;\n }\n\n for (auto& el : hm) {\n int freq = el.second;\n if (freq % 2 == 0) {\n len += freq;\n } else {\n len += freq - 1;\n flag = true;\n }\n }\n\n return flag == true ? len + 1 : len;\n }\n};\n```\n\n---\n\n*Upvote\uD83D\uDC4D and comment\u2328\uFE0F.\nPlease let me know if it helped you.*\n\n**THANK YOU! \uD83D\uDE0A** | 5 | 0 | ['Hash Table', 'String', 'C++', 'Java'] | 1 |
longest-palindrome | C# Solution for Longest Palindrome Problem | c-solution-for-longest-palindrome-proble-j48z | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is similar to the previous one but uses an array ins | Aman_Raj_Sinha | NORMAL | 2024-06-04T03:14:55.567270+00:00 | 2024-06-04T03:14:55.567290+00:00 | 932 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is similar to the previous one but uses an array instead of a HashMap to count character frequencies. This leverages the fact that we are dealing with a fixed set of characters (ASCII values for lowercase and uppercase English letters), making the array a simpler and potentially faster alternative\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tCounting Character Frequencies:\n\t\u2022\tUse an array of size 128 to count the occurrences of each character based on their ASCII values. This array covers all the required characters.\n2.\tConstructing the Palindrome:\n\t\u2022\tIterate through the array of character counts.\n\t\u2022\tIf a character count is even, it can be fully used in the palindrome.\n\t\u2022\tIf a character count is odd, use the even part of it (count - 1) for the palindrome and keep track of the fact that there is at least one character with an odd count.\n3.\tFinal Adjustment:\n\t\u2022\tIf there is at least one character with an odd count, add 1 to the length to account for the center character of the palindrome.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tCounting Characters: O(n), where n is the length of the string. This is because we traverse the string once to count character frequencies.\n\u2022\tCalculating Length: O(1), since we iterate over a fixed-size array of 128 elements, which is constant time.\n\nOverall, the time complexity is O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1), because we use a fixed-size array of 128 elements, which is constant space regardless of the input size.\n\n# Code\n```\npublic class Solution {\n public int LongestPalindrome(string s) {\n // Array to count occurrences of each character\n int[] charCount = new int[128]; // ASCII characters\n \n // Count occurrences of each character\n foreach (char c in s) {\n charCount[c]++;\n }\n \n int length = 0;\n bool hasOddCount = false;\n \n // Iterate through the character counts\n foreach (int count in charCount) {\n if (count % 2 == 0) {\n length += count;\n } else {\n length += count - 1;\n hasOddCount = true;\n }\n }\n \n // If there was any character with an odd count, we can add one more character to the center of the palindrome\n if (hasOddCount) {\n length += 1;\n }\n \n return length;\n }\n}\n``` | 5 | 0 | ['C#'] | 0 |
longest-palindrome | C++ || Hashmap || Simple + Optimal || 0 ms || Beats 100% | c-hashmap-simple-optimal-0-ms-beats-100-6c4w4 | \n# Code\n\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char, int> mp;\n for(auto i : s) {\n mp[i] | meurudesu | NORMAL | 2024-02-10T06:22:12.522698+00:00 | 2024-02-10T06:22:12.522726+00:00 | 596 | false | \n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char, int> mp;\n for(auto i : s) {\n mp[i]++;\n }\n int ans = 0;\n bool isOddPresent = false;\n for(auto i : mp) {\n if(i.second % 2 == 0) ans += i.second;\n else {\n ans += i.second - 1;\n isOddPresent = true;\n }\n }\n if(isOddPresent) ans += 1;\n return ans;\n }\n};\n``` | 5 | 0 | ['Hash Table', 'String', 'Greedy', 'C++'] | 0 |
longest-palindrome | C++ || beginner Friendly || Map | c-beginner-friendly-map-by-inam_28_06-37mq | Method \nusing hash map\nTime Complexity-O(n)\n\n\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n map<char,int>mp;\n int ans=0 | Inam_28_06 | NORMAL | 2023-08-22T03:29:07.824916+00:00 | 2023-08-22T03:29:07.824940+00:00 | 300 | false | Method \nusing hash map\nTime Complexity-O(n)\n\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n map<char,int>mp;\n int ans=0;\n for(int i=0;i<s.size();i++){\n mp[s[i]]++;\n }\n int count=0;\n for(auto i:mp){\n if(i.second%2==1 && count==1){ // when we find one old then convert remaining old to even \n ans=ans+i.second-1;\n }\n else if(i.second%2==1){ // when we find first old then\n count++;\n if(count==1){\n ans=ans+i.second; //add all element beacuse one element are at middle\n }\n }\n else if(i.second%2==0){ //for even case add all element\n ans=ans+i.second;\n }\n \n }\n return ans;\n }\n};\n```\n\n | 5 | 0 | ['C'] | 1 |
longest-palindrome | Easiest Solution || 96% Beats || JavaScript || o(n) | easiest-solution-96-beats-javascript-on-oxp6o | 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 | ayesha_naeem | NORMAL | 2023-08-08T10:52:54.824308+00:00 | 2023-08-08T10:52:54.824334+00:00 | 683 | 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/**\n * @param {string} s\n * @return {number}\n */\nvar longestPalindrome = function(s) {\n let obj ={};\n let answer=0;\n for(let c of s){\n if(!obj[c]){\n obj[c]=1;\n }\n else\n obj[c]++;\n if(obj[c]%2===0){\n answer += 2;\n }\n }\n return s.length>answer ? answer+1 :answer; \n};\n``` | 5 | 0 | ['Hash Table', 'JavaScript'] | 0 |
longest-palindrome | python3 easy to understand solution 98.12% beats with froop | python3-easy-to-understand-solution-9812-gd9j | 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 | ayan_101 | NORMAL | 2023-08-02T02:00:16.288802+00:00 | 2023-08-02T02:00:16.288830+00:00 | 467 | 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\nPlease Upvote !!!!!!!!!!!\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n set_=set()\n for character in s:\n if character not in set_:set_.add(character)\n else:set_.remove(character)\n if len(set_) != 0:return len(s)-len(set_)+1\n else:return len(s)\n``` | 5 | 0 | ['Python3'] | 0 |
longest-palindrome | simple 100% , one loop | simple-100-one-loop-by-adwxsghu-h47b | 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 | adwxsghu | NORMAL | 2023-07-13T10:01:14.421193+00:00 | 2023-07-13T10:01:14.421217+00:00 | 116 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc longestPalindrome(s string) int {\n\tcharMap := make(map[byte]int)\n\tvar length int\n\n\tfor _, c := range []byte(s) {\n\t\tcharMap[c]++\n\t\tnum := charMap[c]\n\t\tif num == 2 {\n\t\t\tlength = length + 2\n\t\t\tdelete(charMap, c)\n\t\t}\n\t}\n\n\n\tif len(charMap) != 0 {\n\t\tlength++\n\t}\n\n\treturn length\n}\n\n``` | 5 | 0 | ['Go'] | 1 |
longest-palindrome | Java solution using HashMap, 9ms | java-solution-using-hashmap-9ms-by-knick-gg07 | \n# Code\n\nclass Solution {\n public int longestPalindrome(String s) {\n int odd_count = 0;\n HashMap<Character, Integer> map = new HashMap<>( | Knickon | NORMAL | 2023-03-16T15:19:28.997289+00:00 | 2023-03-16T15:19:28.997318+00:00 | 2,421 | false | \n# Code\n```\nclass Solution {\n public int longestPalindrome(String s) {\n int odd_count = 0;\n HashMap<Character, Integer> map = new HashMap<>();\n for (char ch: s.toCharArray()){\n map.put(ch, map.getOrDefault(ch, 0) + 1);\n if (map.get(ch) % 2 == 1){\n odd_count ++;\n }\n else{\n odd_count--;\n }\n }\n if (odd_count > 1){\n return s.length() - odd_count + 1;\n }\n return s.length();\n }\n}\n``` | 5 | 0 | ['Hash Table', 'Java'] | 1 |
longest-palindrome | 🚀 100% faster approach, Using Hash Table, BRUTE FORCE | 100-faster-approach-using-hash-table-bru-nw4l | Intuition\n Describe your first thoughts on how to solve this problem. \nIf you see examples, and do a dry run, for each random string, you might see a pattern, | programmer-buddy | NORMAL | 2023-03-07T08:02:51.733481+00:00 | 2023-03-07T08:18:10.529463+00:00 | 1,663 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you see examples, and do a dry run, for each random string, you might see a pattern, which is:\nWhen we have to create a palindrome string, we need **EVEN NUMBER OF CHARACTERS + 1**, so for that, if we just count each character frequency, and check some conditions,\n\n**EXMAPLE**: \nLets, say for a **string s** = "aabbbccdccdddd";\n\nThe frequency will be:\nmap:\na -> 2\nb -> 3\nc -> 4\nd -> 5\n\nAnd now, we just have to add all even number of frequency, and for odd numbers, we just have to ignore 1 and add all odd numbers with - 1;\n\nAnd if we do so, we\'ll get the maximum length of palindrome we can make using input string;\n\nCOUNTER = 0;\n\nEVENS:\na -> 2\nc -> 4\n\nCOUNTER = 2 + 4 = 6;\n\nODDS:\nb -> 3\nd -> 5\n\nCOUNTER = 6 + (5-1) + (3-1) = 12\n\n**AND, RETURN COUNTER + 1;** \n\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a hashmap, and store each character frequency, and sum up each even number of frequency, and odd number of frequency with a, - 1 and by ignoring 1\'s. And in the end return Counter + 1 for certain conditions, otherwise Counter. \n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) or O(52) MAX;\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n // SUGGEST SOME IMPROVEMENTS IN COMMENTS\n int n = s.size(), cnt = 0;\n if(n==1 || n==0) return n;\n if(n==2) {\n if(s[0] == s[1]) return 2;\n return 1;\n } \n\n unordered_map<char, int> mp;\n\n for(auto i:s) {\n ++mp[i];\n }\n\n bool evenExist = false, oneExist = false, oddExist = false;\n\n for(auto i:mp) {\n // IF one exist, that means, we have to ignore it for now\n if(i.second == 1) {\n oneExist = true;\n }\n\n // IF EVEN EXIST, just add it to count;\n else if(i.second%2==0) {\n evenExist = true;\n cnt += i.second;\n }\n\n // If ODD EXIST, and its greater than 2, just add it to count with - 1;\n else if(i.second > 2 && i.second%2 != 0) {\n cnt += i.second-1;\n oddExist = true;\n }\n\n }\n\n // IF EVERY or IF ODD NOT EXIST or If EVEN NOT EXIST or IF NOT ONE EXIST or IF ONLY ODD EXIST\n if(oddExist && evenExist && oneExist || \n !oddExist && evenExist && oneExist || \n oddExist && !evenExist && oneExist ||\n oddExist && evenExist && !oneExist ||\n oddExist && !evenExist && !oneExist) {\n return cnt+1;\n }\n \n else return cnt;\n }\n};\n``` | 5 | 0 | ['Hash Table', 'Greedy', 'C++'] | 2 |
longest-palindrome | Java || 100ms || Easy Approach | java-100ms-easy-approach-by-naveen_kumar-dkuu | \n\n# Approach\n Describe your approach to solving the problem. \n We have to calculate the maximum pair possible from every character.\n Store the occurence of | Naveen_kumar__ | NORMAL | 2023-02-18T14:45:54.399970+00:00 | 2023-02-18T14:45:54.400020+00:00 | 1,290 | false | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* We have to calculate the maximum pair possible from every character.\n* Store the occurence of every character in count array.\n* Then iterate over count array, and let occurence of character is n then do,\n* if n is even then add n. (i.e let n = 4 , then we can use all characters in palindrome string).\n* if n is odd then add n - 1.\n* take a boolean variable (one) which keep tracks that is there any extra character present or not. (i.e not as pair)\n* Then at last, if any extra character is present then return len + 1.\n* Else return len.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n\n# Code\n```\nclass Solution {\n public int longestPalindrome(String s) {\n int[] count = new int[256];\n for(char ch : s.toCharArray()){\n count[ch]++;\n }\n\n boolean one = false;\n int len = 0;\n for(int ele : count){\n if(ele%2 == 0)\n len += ele;\n else{\n len += ele-1;\n one = true;\n }\n }\n return one ? len + 1 : len;\n }\n}\n``` | 5 | 0 | ['Java'] | 2 |
longest-palindrome | C++ solution using hashmap with complete explanation|| Easy to understand | c-solution-using-hashmap-with-complete-e-1qoi | Intuition\nIn palindrome string either all characters occurs even number of times or only one character occurs once and rest occurs even number of times.\n\nTo | jainarihant195 | NORMAL | 2023-01-14T09:09:42.818789+00:00 | 2023-01-14T09:11:01.052275+00:00 | 663 | false | ## Intuition\nIn palindrome string either all characters occurs **even** number of times or only **one** character occurs once and rest occurs even number of times.\n\nTo understand it better : In "abccba" all characters are occuring twice and it is palindrome and in "abcdcba" all characters are occuring twice except d. But it is not possible that two character occur only once in the string to make it palindrome. \n# Approach\nThe first approach that comes to our mind is to create a unordered map. Track the number of times a character is present in string.\nIf a character is present even number of times then all instances of that character can be added in palindrome.\nIf a character is present odd number of times \'n\' then n-1 instances can be added in palindrome. For eg: if a character is present 3 times then 2 instaces of that character can be used in pallindrome.\n\nNow after adding all instances in palindrome, now among all characters which occur odd number of times take only one character.\nFor eg: if a string is given as \'aabbccdefg\' then in palindrome \' \'abc_cba\' either d or e or f or g can occur. \n\nSo, first run a loop to add the number of times a character has occured using map. Now, run loop again and add the conditions mentioned above accordingly.\n\n\n# Complexity\n- Time complexity: O(n) because no nested loops are present.\n\n- Space complexity:O(n) by unordered map.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n //if(s.length()==1) return 1;\n unordered_map<char,int>mp;\n int n=s.length();\n for(int i=0;i<n;i++){\n mp[s[i]]++;\n }\n int length=0;\n for(auto i:mp){\n if(i.second%2==0) length+=i.second;\n else if(i.second>2 && i.second%2==1) length+=i.second-1;\n }\n for(auto i:mp){\n if(i.second%2==1){\n length++;\n break;\n }\n\n }\n return length;\n }\n};\n``` | 5 | 0 | ['Hash Table', 'String', 'C', 'C++'] | 2 |
longest-palindrome | [Ruby] 1-liner, Bit Magic | ruby-1-liner-bit-magic-by-0x81-vthz | ruby\ndef longest_palindrome(s) =\n [s.size, s.each_char.tally.sum { _2 & ~1 } + 1].min\n\nruby\ndef longest_palindrome(s) =\n s.each_char.tally.reduce(0) | 0x81 | NORMAL | 2023-01-04T16:12:17.755143+00:00 | 2023-01-05T06:13:34.560569+00:00 | 162 | false | ```ruby\ndef longest_palindrome(s) =\n [s.size, s.each_char.tally.sum { _2 & ~1 } + 1].min\n```\n```ruby\ndef longest_palindrome(s) =\n s.each_char.tally.reduce(0) do | r, (_, v) |\n r + (v & ~1) | v & 1\n end\n``` | 5 | 0 | ['Ruby'] | 3 |
longest-palindrome | Python3 O(n) using dict | python3-on-using-dict-by-dhuang1993-1hqh | \ndef longestPalindrome(s):\n letters = {}\n \n max = 0\n for c in s:\n if c in letters:\n letters.pop(c)\ | dhuang1993 | NORMAL | 2022-11-08T00:35:51.581051+00:00 | 2022-11-08T00:35:51.581088+00:00 | 611 | false | ```\ndef longestPalindrome(s):\n letters = {}\n \n max = 0\n for c in s:\n if c in letters:\n letters.pop(c)\n max += 2\n else:\n letters[c] = 1\n \n if letters:\n max += 1\n \n return max\n``` | 5 | 0 | [] | 3 |
final-array-state-after-k-multiplication-operations-i | Greedy make_heap vs priority_queue||beats 100% | greedy-make_heap-vs-priority_queuebeats-ypx3x | IntuitionIt's again a question about Greedy using heap/pq.Implement in both in C++ code. Python code uses heapq.heapify.Approach
1st appraoch uses make_heap; it | anwendeng | NORMAL | 2024-12-16T00:30:23.231071+00:00 | 2024-12-16T01:15:37.498045+00:00 | 8,554 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt\'s again a question about Greedy using heap/pq.\n\nImplement in both in C++ code. Python code uses heapq.heapify.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. 1st appraoch uses `make_heap`; it constructs a vector, called `heap`, over the info pairs `(nums[i], i)` \n2. then apply `make_heap` to it w.r.t. `greater` ordering\n3. apply k times pop_heap & push_heap operations, without really pop or push, but just update `heap.back().first*=multiplier`; it\'s more efficient\n4. Transverse over [x, i] in `heap`, let `nums[i]=x`\n5. return `nums`\n6. The 2nd C++ using priority_queue is done & less efficient, but still 0ms & beats 100%\n7. Python is also made by using `heapify` & `heapreplace` with a similar process in 1st C++.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n+k\\log n)$$\npriority_queue: $O((n+k)\\log n)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code |using make_heap C++ 0ms beats 100%| Python using heapify & heapreplace\n```cpp []\nclass Solution {\npublic:\n using int2=pair<int, int>;\n static vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n const int n=nums.size();\n vector<int2> heap(n);\n for(int i=0; i<n; i++){\n heap[i]={nums[i], i};\n }\n make_heap(heap.begin(), heap.end(), greater<>{});\n for(int i=0; i<k; i++){\n pop_heap(heap.begin(), heap.end(), greater<>{});\n heap.back().first*=multiplier;\n push_heap(heap.begin(), heap.end(), greater<>{});\n }\n for(auto& [x, i]: heap)\n nums[i]=x;\n\n return nums;\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n```Python []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n heap=[(x, i) for i, x in enumerate(nums)]\n heapify(heap)\n for _ in range(k):\n x, i=heap[0]\n heapreplace(heap, (x*multiplier, i))\n for x, i in heap:\n nums[i]=x\n return nums\n\n\n \n```\n# C++ using priority_queue||0ms beats 100%\n```\nclass Solution {\npublic:\n using int2=pair<int, int>;\n static vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<int2, vector<int2>, greater<int2>> pq;\n const int n=nums.size();\n for(int i=0; i<n; i++){\n pq.emplace(nums[i],i);\n }\n for(int i=0; i<k; i++){\n auto [x, j]=pq.top();\n pq.pop();\n pq.emplace(multiplier*x, j);\n }\n while(!pq.empty()){\n auto [x,i]=pq.top();\n pq.pop();\n nums[i]=x;\n }\n return nums;\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# There are many questions on Greedy heap/priority_queue with K operations\n[Please turn on English subtitles if necessary [2530. Maximal Score After Applying K Operations](https://leetcode.com/problems/maximal-score-after-applying-k-operations/solutions/5909257/pop-prioriy-queue-til-top-1-86ms-beats-100/)]\n[https://youtu.be/ZfomMqDB4KA?si=Z5Epwcv5nIkQXL-P](https://youtu.be/ZfomMqDB4KA?si=Z5Epwcv5nIkQXL-P)\n[2530. Maximal Score After Applying K Operations](https://leetcode.com/problems/maximal-score-after-applying-k-operations/solutions/5909257/pop-prioriy-queue-til-top-1-86ms-beats-100/)\n[1792. Maximum Average Pass Ratio](https://leetcode.com/problems/maximum-average-pass-ratio/solutions/6147525/greedymake_heap251ms-beats-100-by-anwend-cmr7/)\n[2558. Take Gifts From the Richest Pile](https://leetcode.com/problems/take-gifts-from-the-richest-pile/solutions/6137511/make_heap-accumulatebeats-100-by-anwende-aowi/) | 27 | 0 | ['Array', 'Heap (Priority Queue)', 'Simulation', 'C++', 'Python3'] | 8 |
final-array-state-after-k-multiplication-operations-i | O(N*N)->O(K*log(N)) Video Solution 🔥 || How to 🤔 in Interview || Priority_queue | onn-oklogn-video-solution-how-to-in-inte-8mvu | If you like the solution Please Upvote and subscribe to my youtube channel\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nDry Run | ayushnemmaniwar12 | NORMAL | 2024-08-25T06:52:13.215634+00:00 | 2024-08-25T07:16:37.463791+00:00 | 3,690 | false | ***If you like the solution Please Upvote and subscribe to my youtube channel***\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDry Run few examples and observe how you can optimize further\n\n\n\n***Easy Video Explanation***\n\nhttps://youtu.be/YxRD34k_Oog\n\n# Brute Force\n\n\n```C++ []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& v, int k, int m) {\n int n = v.size();\n while(k--) {\n int idx=0,ans=v[0];\n for(int i=1;i<n;i++) {\n if(v[i]<ans) {\n ans=v[i];\n idx=i;\n }\n }\n v[idx]=v[idx]*m;\n //cout<<idx<<" "<<v[idx]<<endl;\n }\n return v;\n }\n};\n```\n```python []\ndef get_final_state(self, v, k, m):\n n = len(v)\n for _ in range(k):\n idx = 0\n ans = v[0]\n for i in range(1, n):\n if v[i] < ans:\n ans = v[i]\n idx = i\n v[idx] *= m\n return v\n```\n```Java []\npublic List<Integer> getFinalState(List<Integer> v, int k, int m) {\n int n = v.size();\n while (k-- > 0) {\n int idx = 0;\n int ans = v.get(0);\n for (int i = 1; i < n; i++) {\n if (v.get(i) < ans) {\n ans = v.get(i);\n idx = i;\n }\n }\n v.set(idx, v.get(idx) * m);\n }\n return v;\n }\n\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*K)\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Using Priority Queue\n\n\n```C++ []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& v, int k, int m) {\n int n = v.size();\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;\n for(int i=0;i<n;i++) {\n q.push({v[i],i});\n }\n while(k--) {\n pair<int,int>p=q.top();\n q.pop();\n int val=p.first;\n int idx = p.second;\n v[idx]=val*m;\n q.push({val*m,idx});\n }\n return v;\n }\n};\n```\n```python []\nimport heapq\n\nclass Solution:\n def get_final_state(self, v, k, m):\n n = len(v)\n q = [(v[i], i) for i in range(n)]\n heapq.heapify(q)\n \n while k > 0:\n val, idx = heapq.heappop(q)\n v[idx] = val * m\n heapq.heappush(q, (val * m, idx))\n k -= 1\n \n return v\n\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n public List<Integer> getFinalState(List<Integer> v, int k, int m) {\n int n = v.size();\n PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n \n for (int i = 0; i < n; i++) {\n q.offer(new int[]{v.get(i), i});\n }\n \n while (k-- > 0) {\n int[] p = q.poll();\n int val = p[0];\n int idx = p[1];\n v.set(idx, val * m);\n q.offer(new int[]{val * m, idx});\n }\n \n return v;\n }\n}\n\n\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(K*log(N))\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos***\n\n*Thank you* \uD83D\uDE00 | 24 | 2 | ['Heap (Priority Queue)', 'C++', 'Java', 'Python3'] | 7 |
final-array-state-after-k-multiplication-operations-i | Python 3 || 8 lines, heap || T/S: 95% / 21% | python-3-8-lines-heap-ts-95-21-by-spauld-of24 | \npython3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n\n heap = list(zip(nums, range(len(nu | Spaulding_ | NORMAL | 2024-08-25T15:31:09.026284+00:00 | 2024-08-28T04:28:48.587009+00:00 | 622 | false | \n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n\n heap = list(zip(nums, range(len(nums))))\n heapify(heap)\n\n while k:\n num, idx = heappop(heap)\n heappush(heap,(num * multiplier, idx))\n k-=1\n\n heap.sort(key = lambda x: x[1])\n \n return list(zip(*heap))[0]\n```\n[https://leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/submissions/1368009614/](https://leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/submissions/1368009614/)\n\nI could be wrong, but I think that time complexity is *O*(*N* log *N* + *K* log *N*) and space complexity is *O*(*N*), in which *N* ~ `len(nums)` and *K* ~ `k`. | 16 | 0 | ['Python3'] | 2 |
final-array-state-after-k-multiplication-operations-i | Beat 100% | Solution for LeetCode#3264 | beat-100-solution-for-leetcode3264-by-sa-s7f2 | IntuitionThe problem requires finding the minimum element in the array, multiplying it by a given factor, and repeating this process k times. The intuition is t | samir023041 | NORMAL | 2024-12-16T00:39:28.494895+00:00 | 2024-12-16T00:39:28.494895+00:00 | 3,526 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the minimum element in the array, multiplying it by a given factor, and repeating this process k times. The intuition is to use a simple iterative approach to find and update the minimum element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a helper function getMin to find the minimum element and its index in the array.\n2. Iterate k times:\n\t- Find the minimum element and its index using getMin.\n\t- Update the element at that index by multiplying it with the given multiplier.\n3. Return the modified array.\n\t\n\n# Complexity\n- Time complexity: O(n * k)\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 Option-01\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int[] arr=new int[2];\n \n for(int i=0; i<k; i++){\n arr=getMin(nums);\n nums[arr[1]]=arr[0]*multiplier;\n }\n \n return nums;\n } \n \n int[] getMin(int[] nums){\n int min=Integer.MAX_VALUE;\n int idx=0;\n for(int i=0; i<nums.length; i++){\n if(nums[i]<min){\n min=nums[i];\n idx=i;\n }\n }\n \n return new int[]{min,idx};\n }\n \n}\n```\n\n\n# Code Option-02\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int n=nums.length;\n PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->a[0]==b[0]?a[1]-b[1]:a[0]-b[0]);\n\n for(int i=0; i<n; i++){\n pq.add(new int[]{nums[i],i});\n }\n\n \n for(int i=0; i<k; i++){\n int[] arr=pq.poll();\n int val=arr[0];\n int idx=arr[1];\n\n nums[idx]=val*multiplier;\n pq.add(new int[]{nums[idx],idx});\n }\n\n \n return nums;\n } \n \n \n \n}\n``` | 12 | 0 | ['Heap (Priority Queue)', 'Java'] | 3 |
final-array-state-after-k-multiplication-operations-i | ✅Simple Solution | Beginner Friendly | Easy Approach with Explanation✅ | simple-solution-beginner-friendly-easy-a-vmqy | IntuitionThe problem requires modifying an array by iteratively finding and multiplying the minimum element. The key insight is to repeatedly identify the small | Jithinp96 | NORMAL | 2024-12-16T03:56:49.193533+00:00 | 2024-12-16T03:56:49.193533+00:00 | 1,686 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires modifying an array by iteratively finding and multiplying the minimum element. The key insight is to repeatedly identify the smallest element and transform it using a given multiplier for a specified number of iterations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through the array `k` times\n2. In each iteration:\n - Find the index of the minimum element in the current array\n - Multiply the minimum element by the given multiplier\n3. Return the modified array after `k` iterations\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} multiplier\n * @return {number[]}\n */\nvar getFinalState = function(nums, k, multiplier) {\n for(let i = 0; i < k; ++i) {\n let index = nums.indexOf(Math.min(...nums))\n nums[index] *= multiplier\n }\n return nums\n};\n```\n\n```typescript []\nfunction getFinalState(nums: number[], k: number, multiplier: number): number[] {\n for(let i = 0; i < k; ++i) {\n let index = nums.indexOf(Math.min(...nums))\n nums[index] *= multiplier\n }\n return nums\n};\n```\n\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n for(int i = 0; i < k; ++i) {\n auto minIt = min_element(nums.begin(), nums.end());\n *minIt *= multiplier;\n }\n return nums;\n }\n};\n```\n\n``` c []\nint* getFinalState(int* nums, int numsSize, int k, int multiplier, int* returnSize) {\n *returnSize = numsSize;\n int* result = (int*)malloc(numsSize * sizeof(int));\n \n for(int i = 0; i < numsSize; i++) {\n result[i] = nums[i];\n }\n \n for(int i = 0; i < k; ++i) {\n int minIndex = 0;\n for(int j = 1; j < numsSize; j++) {\n if(result[j] < result[minIndex]) {\n minIndex = j;\n }\n }\n result[minIndex] *= multiplier;\n }\n \n return result;\n}\n | 10 | 0 | ['C', 'C++', 'TypeScript', 'JavaScript'] | 1 |
final-array-state-after-k-multiplication-operations-i | 💢☠💫Easiest👾💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅☠🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-vdz5 | Intuition
ApproachComplexity
Time complexity:
Space complexity:
Code | Edwards310 | NORMAL | 2024-08-25T11:45:02.020288+00:00 | 2024-12-16T14:37:25.718713+00:00 | 809 | false | # Intuition\n\n\n\n```javascript []\n//JavaScript Code\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} multiplier\n * @return {number[]}\n */\nvar getFinalState = function(nums, k, multiplier) {\n while(k--){\n let ans = nums[0], idx = 0;\n for(let i = 0; i < nums.length; i++)\n if(nums[i] < ans){\n ans = nums[i];\n idx = i;\n }\n nums[idx] *= multiplier;\n }\n return nums\n};\n```\n```C++ []\n//C++ Code\n// Start Of Edwards310\'s Template...\n#pragma GCC optimize("O2")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef vector<int> vi;\n\n#define Rep1(i, n) FOR1(i, 1, n)\n#define WHL(i, n) while (i < n)\n#define ALL(v) v.begin(), v.end()\n#define SORT(v) sort(ALL(v))\n#define REVERSE(v) reverse(ALL(v))\n#define mxe(v) max_element(ALL(v))\n#define mie(v) min_element(ALL(v))\n\n// End of Edwards310 Template\nclass Solution {\npublic:\n vi getFinalState(vector<int>& nums, int k, int multiplier) {\n while(k--){\n auto ele = mie(nums);\n *ele *= multiplier;\n }\n return nums;\n }\n};\n```\n```Python3 []\n#Python3 Code\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n for _ in range(k):\n idx = nums.index(min(nums))\n nums[idx] *= multiplier\n return nums\n \n```\n```Java []\n//Java Code\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int n = nums.length;\n while(k-- != 0){\n int ans = nums[0], idx = 0;\n for(int i = 0; i < n; i++){\n if(nums[i] < ans){\n ans = nums[i];\n idx = i;\n }\n \n }\n nums[idx] *= multiplier;\n }\n return nums;\n }\n}\n```\n```C []\n//C Code\n#define Rep(i, n) for(int i = 0; i < n; i++)\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* getFinalState(int* nums, int numsSize, int k, int multiplier, int* returnSize) {\n while(k--){\n int val = nums[0], idx = 0;\n Rep(i, numsSize)\n nums[i] < val ? (val = nums[i], idx = i) : 0;\n nums[idx] *= multiplier;\n }\n *returnSize = numsSize;\n return nums;\n}\n```\n```Go []\nfunc getFinalState(nums []int, k int, multiplier int) []int {\n n := len(nums)\n for i := 0; i < k; i++ {\n ans, idx := nums[0], 0\n for j := 0; j < n; j++ {\n if nums[j] < ans {\n ans = nums[j]\n idx = j\n }\n }\n nums[idx] *= multiplier\n }\n return nums\n}\n```\n```Python []\n#Python Code\nclass Solution(object):\n def getFinalState(self, nums, k, multiplier):\n """\n :type nums: List[int]\n :type k: int\n :type multiplier: int\n :rtype: List[int]\n """\n while k:\n idx = nums.index(min(nums))\n nums[idx] *= multiplier\n k -= 1\n return nums\n```\n```C# []\n//C# Code\npublic class Solution {\n public int[] GetFinalState(int[] nums, int k, int multiplier) {\n int n = nums.Length;\n while(k-- != 0){\n int ans = nums[0], idx = 0;\n for(int i = 0; i < n; i++){\n if(nums[i] < ans){\n ans = nums[i];\n idx = i;\n }\n \n }\n nums[idx] *= multiplier;\n }\n return nums;\n }\n}\n```\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 O(K * N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n\n | 9 | 1 | ['Array', 'String', 'C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#'] | 1 |
final-array-state-after-k-multiplication-operations-i | Python | Greedy Pattern | python-greedy-pattern-by-khosiyat-uapm | see the Successfully Accepted SubmissionCodeExplanationInitialization and Loop:
The function performs k operations.
For each operation, it identifies the minimu | Khosiyat | NORMAL | 2024-12-16T04:07:37.234474+00:00 | 2024-12-16T04:07:37.234474+00:00 | 397 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/submissions/1479879843/?envType=daily-question&envId=2024-12-16)\n\n# Code\n```python3 []\nfrom typing import List\n\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n for _ in range(k):\n # Find the index of the minimum value. If there are multiple, pick the first one.\n min_index = 0\n for i in range(1, len(nums)):\n if nums[i] < nums[min_index]:\n min_index = i\n \n # Update the minimum value by multiplying it with the multiplier\n nums[min_index] *= multiplier\n\n return nums\n\n```\n\n## Explanation\n\n### Initialization and Loop:\n- The function performs `k` operations.\n- For each operation, it identifies the minimum value in the array `nums`.\n\n### Finding the Minimum Value:\n- A simple loop is used to find the index of the smallest element.\n- If there are multiple occurrences of the minimum value, the loop ensures that the first occurrence is chosen.\n\n### Updating the Minimum Value:\n- The value at the identified index is multiplied by the given multiplier.\n\n### Return the Final Array:\n- After all `k` operations, the updated `nums` array is returned.\n\n## Complexity:\n\n### Time Complexity:\n- Finding the minimum takes \\(O(n)\\) per operation, where \\(n\\) is the length of `nums`.\n- Total time complexity is \\(O(k \\times n)\\).\n\n### Space Complexity:\n- \\(O(1)\\), as no extra space is used beyond the input array.\n\n\n\n | 8 | 0 | ['Python3'] | 0 |
final-array-state-after-k-multiplication-operations-i | EASIEST PYTHON CODE || BEATS 100% ✅ | easiest-python-code-beats-100-by-prathik-vea9 | IntuitionThe question was to find the minimum number and multiply it in-place for k times. So we need an iterative loop, find the minimum number & multiply it.A | PrathikRKrishnan | NORMAL | 2024-12-16T02:05:10.411999+00:00 | 2024-12-16T02:05:10.411999+00:00 | 1,004 | false | \n\n# Intuition\nThe question was to find the minimum number and multiply it in-place for k times. So we need an iterative loop, find the minimum number & multiply it.\n\n# Approach\nSo we first create a for loop to loop k times.\n```\nfor _ in range(k):\n```\nNow, we find the minimum number and store the index of that number in a variable x. pretty straight forward, we use .index() and min() to do this.\n```\nx=nums.index(min(nums))\n```\nApply the multiplier by indexing.\n```\nnums[x]*=multiplier\n```\n\n# Complexity\n- Time complexity : O(K\u2217N)\n\n- Space complexity : O(1)\n\n# Code\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n for _ in range(k):\n x=nums.index(min(nums))\n nums[x]*=multiplier\n return nums\n```\n\nPlease consider upvoting! | 8 | 0 | ['Python3'] | 1 |
final-array-state-after-k-multiplication-operations-i | 100% Beats 🚀 Beginner Detailed Solution 🧠 | 100-beats-beginner-detailed-solution-by-v7ylh | 🧠 IntuitionThe problem involves transforming an array by performing k operations, where the smallest element (breaking ties by index) is multiplied by a given m | Sumeet_Sharma-1 | NORMAL | 2024-12-16T01:41:35.288237+00:00 | 2024-12-16T01:41:35.288237+00:00 | 5,312 | false | # \uD83E\uDDE0 Intuition\n<!-- \uD83D\uDE80 Describe your first thoughts on how to solve this problem. -->\nThe problem involves transforming an array by performing `k` operations, where the smallest element (breaking ties by index) is multiplied by a given multiplier. To efficiently track the smallest element and its index, a **min-heap** is an ideal choice.\n\n# \uD83D\uDD0D Approach\n<!-- \uD83D\uDCDD Describe your approach to solving the problem. -->\n1. Use a **priority queue (min-heap)** to store elements along with their indices as pairs.\n - Sort the heap primarily by element value and secondarily by index (for ties).\n2. For each operation:\n - Extract the smallest element from the heap.\n - Multiply the element by the given multiplier.\n - Push the updated element back into the heap.\n3. After processing all operations, update the array based on the elements in the heap.\n\n# \u23F1\uFE0F Complexity\n- **Time Complexity:** \n - Building the heap: $$O(n \\log n)$$ \n - Each operation: $$O(k \\log n)$$ \n - Total: $$O((n + k) \\log n)$$ \n\n\n- **Space Complexity:** \n - $$O(n)$$ (for the heap).\n \n\n\n \n\n# \uD83D\uDCBB Code\n```cpp []\nclass Solution {\npublic:\n struct compare {\n bool operator()(pair<int, int> a, pair<int, int> b) {\n if (a.first == b.first) {\n return a.second > b.second;\n }\n return a.first > b.first;\n }\n };\n\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq;\n for (int i = 0; i < nums.size(); i++) {\n pq.push({nums[i], i});\n }\n while (k--) {\n auto Y = pq.top();\n pq.pop();\n pq.push({Y.first * multiplier, Y.second});\n }\n while (!pq.empty()) {\n auto to = pq.top();\n pq.pop();\n nums[to.second] = to.first;\n }\n return nums;\n }\n};\n```\n```Java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n // Custom comparator for the priority queue\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> {\n if (a[0] == b[0]) {\n return Integer.compare(a[1], b[1]); // Compare by index if values are the same\n }\n return Integer.compare(a[0], b[0]); // Compare by value\n });\n\n // Push all elements along with their indices into the priority queue\n for (int i = 0; i < nums.length; i++) {\n pq.add(new int[] { nums[i], i });\n }\n\n // Perform k operations\n while (k-- > 0) {\n int[] smallest = pq.poll(); // Get the smallest element\n smallest[0] *= multiplier; // Multiply the value\n pq.add(smallest); // Add it back to the priority queue\n }\n\n // Update the original array based on the final state in the priority queue\n while (!pq.isEmpty()) {\n int[] entry = pq.poll();\n nums[entry[1]] = entry[0];\n }\n\n return nums;\n }\n}\n```\n```Python3 []\nfrom heapq import heappush, heappop\nfrom typing import List\n\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n # Priority queue (min-heap) to store pairs of (value, index)\n pq = []\n for i, num in enumerate(nums):\n heappush(pq, (num, i))\n\n # Perform k operations\n while k > 0:\n value, idx = heappop(pq) # Get the smallest element\n value *= multiplier # Multiply the value\n heappush(pq, (value, idx)) # Push it back to the heap\n k -= 1\n\n # Update the original array with the final values from the heap\n while pq:\n value, idx = heappop(pq)\n nums[idx] = value\n\n return nums\n```\n```C []\n#include <stdlib.h>\n\n// Define a structure to store the value and index\ntypedef struct {\n int value;\n int index;\n} Pair;\n\n// Comparator function for the priority queue (min-heap)\nint compare(const void* a, const void* b) {\n Pair* p1 = (Pair*)a;\n Pair* p2 = (Pair*)b;\n if (p1->value == p2->value) {\n return p1->index - p2->index; // Compare by index if values are the same\n }\n return p1->value - p2->value; // Compare by value\n}\n\nvoid heapify(Pair* heap, int size, int i) {\n int smallest = i;\n int left = 2 * i + 1;\n int right = 2 * i + 2;\n\n if (left < size && compare(&heap[left], &heap[smallest]) < 0) {\n smallest = left;\n }\n if (right < size && compare(&heap[right], &heap[smallest]) < 0) {\n smallest = right;\n }\n if (smallest != i) {\n Pair temp = heap[i];\n heap[i] = heap[smallest];\n heap[smallest] = temp;\n heapify(heap, size, smallest);\n }\n}\n\nvoid heapPush(Pair* heap, int* size, Pair p) {\n heap[(*size)++] = p;\n for (int i = (*size - 1) / 2; i >= 0; i--) {\n heapify(heap, *size, i);\n }\n}\n\nPair heapPop(Pair* heap, int* size) {\n Pair root = heap[0];\n heap[0] = heap[--(*size)];\n heapify(heap, *size, 0);\n return root;\n}\n\nint* getFinalState(int* nums, int numsSize, int k, int multiplier, int* returnSize) {\n Pair* heap = (Pair*)malloc(numsSize * sizeof(Pair));\n int heapSize = 0;\n\n // Initialize the heap with array values and their indices\n for (int i = 0; i < numsSize; i++) {\n heapPush(heap, &heapSize, (Pair){nums[i], i});\n }\n\n // Perform k operations\n while (k-- > 0) {\n Pair smallest = heapPop(heap, &heapSize);\n smallest.value *= multiplier;\n heapPush(heap, &heapSize, smallest);\n }\n\n // Update the original array based on the final heap state\n while (heapSize > 0) {\n Pair p = heapPop(heap, &heapSize);\n nums[p.index] = p.value;\n }\n\n free(heap);\n *returnSize = numsSize;\n return nums;\n}\n```\n```C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n public int[] GetFinalState(int[] nums, int k, int multiplier) {\n // Priority queue to store pairs of value and index\n var pq = new SortedSet<(int value, int index)>(Comparer<(int value, int index)>.Create((a, b) =>\n a.value == b.value ? a.index.CompareTo(b.index) : a.value.CompareTo(b.value)));\n\n // Initialize the priority queue with array elements and their indices\n for (int i = 0; i < nums.Length; i++) {\n pq.Add((nums[i], i));\n }\n\n // Perform k operations\n while (k-- > 0) {\n var smallest = pq.Min; // Get the smallest element\n pq.Remove(smallest); // Remove it from the priority queue\n\n // Update the value and re-add it to the priority queue\n pq.Add((smallest.value * multiplier, smallest.index));\n }\n\n // Update the original array with the final values from the priority queue\n foreach (var item in pq) {\n nums[item.index] = item.value;\n }\n\n return nums;\n }\n}\n```\n```JavaScript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} multiplier\n * @return {number[]}\n */\nvar getFinalState = function(nums, k, multiplier) {\n // Priority queue implementation using a Min-Heap\n const heap = [];\n \n // Helper functions for the heap\n const heapPush = (val, idx) => {\n heap.push({ val, idx });\n let currentIndex = heap.length - 1;\n while (currentIndex > 0) {\n let parentIndex = Math.floor((currentIndex - 1) / 2);\n if (heap[parentIndex].val > heap[currentIndex].val ||\n (heap[parentIndex].val === heap[currentIndex].val && heap[parentIndex].idx > heap[currentIndex].idx)) {\n [heap[parentIndex], heap[currentIndex]] = [heap[currentIndex], heap[parentIndex]];\n currentIndex = parentIndex;\n } else {\n break;\n }\n }\n };\n\n const heapPop = () => {\n const top = heap[0];\n const end = heap.pop();\n if (heap.length > 0) {\n heap[0] = end;\n let index = 0;\n while (true) {\n let left = 2 * index + 1;\n let right = 2 * index + 2;\n let smallest = index;\n\n if (left < heap.length && (heap[left].val < heap[smallest].val ||\n (heap[left].val === heap[smallest].val && heap[left].idx < heap[smallest].idx))) {\n smallest = left;\n }\n if (right < heap.length && (heap[right].val < heap[smallest].val ||\n (heap[right].val === heap[smallest].val && heap[right].idx < heap[smallest].idx))) {\n smallest = right;\n }\n if (smallest === index) break;\n [heap[index], heap[smallest]] = [heap[smallest], heap[index]];\n index = smallest;\n }\n }\n return top;\n };\n\n // Initialize the heap with the array values and indices\n nums.forEach((num, idx) => heapPush(num, idx));\n\n // Perform k operations\n while (k-- > 0) {\n let smallest = heapPop();\n heapPush(smallest.val * multiplier, smallest.idx);\n }\n\n // Update the original array based on the heap state\n while (heap.length > 0) {\n let { val, idx } = heapPop();\n nums[idx] = val;\n }\n\n return nums;\n};\n```\n```Ruby []\n# @param {Integer[]} nums\n# @param {Integer} k\n# @param {Integer} multiplier\n# @return {Integer[]}\ndef get_final_state(nums, k, multiplier)\n # Define a priority queue using an array\n pq = nums.each_with_index.map { |num, idx| [num, idx] }\n\n # Custom sorting for the priority queue\n pq.sort_by! { |x| [x[0], x[1]] }\n\n # Perform k operations\n k.times do\n smallest = pq.shift # Remove the smallest element\n smallest[0] *= multiplier # Update its value\n pq.push(smallest) # Push it back to the priority queue\n pq.sort_by! { |x| [x[0], x[1]] } # Re-sort the queue\n end\n\n # Update the original array based on the modified priority queue\n pq.each do |value, index|\n nums[index] = value\n end\n\n nums\nend\n```\n | 8 | 0 | ['Heap (Priority Queue)', 'C++', 'Java', 'Python3', 'Ruby', 'JavaScript', 'C#'] | 6 |
final-array-state-after-k-multiplication-operations-i | Easyyy Pessyyy Solution ✅| Beats 100 % Runtime 🔥 | Memory 97.81% 🔥 | easyyy-pessyyy-solution-beats-100-runtim-rs79 | IntuitionThe problem involves repeatedly modifying the smallest element in an array k times by multiplying it by a given multiplier. To achieve this:
Finding th | jaitaneja333 | NORMAL | 2024-12-16T05:48:37.160670+00:00 | 2024-12-16T05:48:37.160670+00:00 | 1,169 | false | \n\n# Intuition\nThe problem involves repeatedly modifying the smallest element in an array k times by multiplying it by a given multiplier. To achieve this:\n\n1. Finding the smallest element: At each step, identify the smallest element in the array. This is achieved by iterating through the array and keeping track of the smallest value and its index.\n2. Updating the smallest element: Replace the smallest element with its value multiplied by the given multiplier.\n3. Repetition: Repeat the above steps k times.\n* The solution employs a straightforward greedy approach: always operate on the smallest element at each iteration, ensuring that the transformation of the array is consistent with the problem\'s requirements.\n\n# Approach\n* Iterate k times: For each of the k iterations:\n* Traverse the entire array to locate the smallest element.\n* Update the smallest element by multiplying it with the multiplier.\nReturn the updated array: After completing k operations, return the modified array.\n\n# Complexity\n### Time complexity: `O(k\u22C5n)`\n* For each of the k iterations, the algorithm traverses the entire array of size n to find the smallest element.\n* This results in a total time complexity of O(k\u22C5n).\n\n### Space complexity: `O(1)`\n* The algorithm does not use any additional data structures apart from the input array, resulting in O(1) extra space usage (in-place updates).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while(k--){\n int num = nums[0];\n int index = 0;\n for(int i = 1; i < nums.size(); i++){\n if(nums[i] < num){\n num = nums[i];\n index = i;\n }\n }\n nums[index] = nums[index]*multiplier;\n }\n return nums;\n }\n};\n```\n```Java [Java]\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n while (k-- > 0) {\n int num = nums[0];\n int index = 0;\n\n \n for (int i = 1; i < nums.length; i++) {\n if (nums[i] < num) {\n num = nums[i];\n index = i;\n }\n }\n\n \n nums[index] = nums[index] * multiplier;\n }\n return nums;\n }\n}\n\n```\n\n | 7 | 0 | ['Array', 'Math', 'C++', 'Java'] | 2 |
final-array-state-after-k-multiplication-operations-i | Beats 100%✅✅|| Easy Priority Queue Solution | beats-100-easy-priority-queue-solution-b-kuui | IntuitionThe problem involves modifying the array nums iteratively based on certain conditions. Using a priority queue allows us to efficiently track the smalle | arunk_leetcode | NORMAL | 2024-12-16T04:26:50.484259+00:00 | 2024-12-16T04:26:50.484259+00:00 | 1,431 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves modifying the array `nums` iteratively based on certain conditions. Using a priority queue allows us to efficiently track the smallest element, which will help in making the modifications systematically.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use a **min-heap (priority queue)** to store the elements of the array along with their indices. This allows us to efficiently retrieve the smallest element.\n2. Perform `k` iterations:\n - Extract the smallest element from the priority queue.\n - Modify the element by multiplying it with `m`.\n - Update the value in the array.\n - Push the updated value back into the priority queue.\n3. After `k` iterations, return the modified array.\n\nThis approach ensures that the smallest element is always prioritized for modification, leading to an efficient solution.\n\n# Complexity\n- Time complexity: $$O(n \\log n + k \\log n)$$ \n - Building the priority queue takes $$O(n \\log n)$$.\n - Each of the `k` iterations involves a pop and push operation, each taking $$O(\\log n)$$.\n\n- Space complexity: $$O(n)$$ \n - The priority queue stores `n` elements.\n\n# Code\n```cpp\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int m) {\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n for(int i = 0; i < nums.size(); i++) {\n pq.push({nums[i], i});\n }\n while(k--) {\n auto it = pq.top();\n pq.pop();\n nums[it.second] = m * it.first;\n pq.push({m * it.first, it.second}); \n }\n return nums;\n }\n};\n | 7 | 0 | ['Two Pointers', 'Heap (Priority Queue)', 'C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | [c++, Java] Using minHeap solution | using-priority-queue-by-kreakemp-fgyl | Approach :
Simply simulate what has been asked using a minHeap ( priority queue )
Code Here is an article of my last interview experience - A Journey to FAANG C | kreakEmp | NORMAL | 2024-08-25T04:42:33.861326+00:00 | 2024-12-16T07:13:17.274285+00:00 | 328 | false | # Approach : \n- Simply simulate what has been asked using a minHeap ( priority queue )\n\n# Code\n```cpp []\nvector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<pair<int,int>, vector<pair<int, int>>, greater<pair<int,int>>> pq;\n for(auto i = 0; i < nums.size(); ++i) pq.push({nums[i], i});\n for(int i = 0; i < k; ++i){\n auto [num, ind] = pq.top(); pq.pop();\n nums[ind] = num * multiplier;\n pq.push({nums[ind], ind});\n }\n return nums;\n}\n```\n```java []\nint[] getFinalState(int[] nums, int k, int multiplier) {\n PriorityQueue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>((a, b) -> {\n int valueComparison = Integer.compare(a.getKey(), b.getKey());\n if (valueComparison == 0) return Integer.compare(a.getValue(), b.getValue());\n return valueComparison;\n });\n for(int i = 0; i < nums.length; ++i) minHeap.add(new Pair<>(nums[i], i));\n while(k-- > 0){\n Pair p = minHeap.poll();\n nums[(int)p.getValue()] = (int)p.getKey() * multiplier;\n minHeap.add(new Pair<>(nums[(int)p.getValue()], (int)p.getValue()));\n }\n return nums;\n}\n```\n\n---\n\n<b> Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n--- | 7 | 1 | ['C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | C++ || O(k*n) || O(k*logN) | c-okn-oklogn-by-abhay5349singh-p8q6 | Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\nApproach:\n get minimum value from array for each k\n update minimum value after mul | abhay5349singh | NORMAL | 2024-08-25T04:01:00.135379+00:00 | 2024-08-25T04:01:00.135410+00:00 | 815 | false | **Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n**Approach:**\n* get minimum value from array for each k\n* update minimum value after multiplying\n\n```\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int mul) {\n while(k--){\n int mine = *min_element(nums.begin(),nums.end());\n int idx = -1;\n for(int i=0;i<nums.size();i++){\n if(nums[i] == mine){\n nums[i] *= mul;\n break;\n }\n }\n }\n return nums;\n }\n};\n```\n\n**Approach:**\n* add all values to `min heap`\n* for each k, pop top value (as it will be minimum) and update minimum value after multiplying\n\n```\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int mul) {\n priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n\n for (int i = 0; i < nums.size(); ++i) {\n pq.push({(long long)nums[i], i}); \n }\n\n while (k--) {\n auto [value, idx] = pq.top();\n pq.pop();\n \n value *= mul; \n nums[idx] = value;\n \n pq.push({value, idx}); \n }\n\n return nums;\n }\n};\n```\n\n**Do upvote if it helps :)** | 7 | 3 | [] | 2 |
final-array-state-after-k-multiplication-operations-i | Python | Using built-in fuctions | Beats 98.84% | python-using-built-in-fuctions-beats-988-yicj | Complexity\n- Time complexity: O(n*k)\n\n- Space complexity: O(1)\n\n# Code\npython3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, m | vish501 | NORMAL | 2024-09-25T07:47:15.657388+00:00 | 2024-09-25T07:47:15.657418+00:00 | 81 | false | # Complexity\n- Time complexity: $$O(n*k)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n for _ in range(k):\n nums[nums.index(min(nums))] *= multiplier\n return nums\n``` | 5 | 0 | ['Array', 'Math', 'Python3'] | 1 |
final-array-state-after-k-multiplication-operations-i | Simple and Easy C++ Code || ☠️💯 | simple-and-easy-c-code-by-shodhan_ak-964n | \n# Code\ncpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while (k != 0) {\n au | Shodhan_ak | NORMAL | 2024-08-25T14:19:16.000718+00:00 | 2024-08-25T14:19:16.000790+00:00 | 632 | false | \n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while (k != 0) {\n auto it = min_element(nums.begin(), nums.end());\n *it *= multiplier;\n k--;\n }\n return nums;\n }\n};\n\n```\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe getFinalState function is designed to transform an array of integers nums based on a specified number of operations k and a multiplier. The goal is to repeatedly apply a multiplier to the smallest element in the array k times.\n\n**Here\u2019s the intuition behind the function:**\n\n**Finding the Smallest Element:** \nEach operation involves finding the smallest element in the array. This ensures that the smallest element is scaled up first, which helps in maintaining a certain balance in the array as we perform operations.\n\n**Applying the Multiplier:** \nOnce the smallest element is identified, it is multiplied by the given multiplier. This operation alters the value of the smallest element, which might change its relative position in the array for subsequent operations.\n\n**Repeating the Process:**\nThe process is repeated k times. Each time, the smallest element (which may have changed due to previous operations) is multiplied.\n\n**Returning the Result:**\nAfter completing all k operations, the modified array is returned as the final state.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n**Initialization:**\n\nStart with the input array nums, the number of operations k, and the multiplier multiplier.\n\n**Iterate Through Operations:**\n\nUse a loop to perform the operation exactly k times.\n\n**Find the Minimum Element:**\n\nIn each iteration, find the smallest element in the array using the min_element function. This function returns an iterator pointing to the smallest element.\n\n**Apply the Multiplier:**\n\nDereference the iterator to access the smallest element and multiply it by the multiplier. This updates the value of the smallest element in the array.\n\n**Repeat:**\n\nContinue the above steps until the loop completes k iterations.\n\n**Return the Final State:**\n\nAfter completing all operations, return the modified array nums.\n\n# Complexity\n- Time complexity: The time complexity of finding the minimum element\nO(n) where n is the size of the array. Since this operation is performed k times, the overall time complexity is O(k\u22C5n).\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 | 5 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅100 % fastest ✅Detailed Explanation💯✅Easy And Simple Solution ✅Clean Code ✅ Beginner Friendly | 100-fastest-detailed-explanationeasy-and-u7pm | Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\nFoll | ayushluthra62 | NORMAL | 2024-08-25T04:00:41.813057+00:00 | 2024-08-25T04:00:41.813085+00:00 | 868 | false | ***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]**\n\n# Approach :\nApproach is very simple: we have to do k operations, so in every operation, we will find the minimum element from nums, multiply it by the multiplier, and update the nums array.\n\n# Complexity\n- Time complexity:\nO( K * N)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n \n for(int i = 0; i<k; i++){\n int miniElement = INT_MAX;\n int index = -1;\n for(int j =0; j<nums.size();j++){\n if(miniElement > nums[j]) {\n miniElement = nums[j];\n index = j;\n }\n \n }\n nums[index] = nums[index] * multiplier;\n \n \n }\n \n return nums;\n }\n};\n```\n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]** | 5 | 0 | ['Math', 'C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | ✅ One Line Solution | one-line-solution-by-mikposp-2xtv | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)CodeTime complexity: O(n∗k). Space complexity: O(n). | MikPosp | NORMAL | 2024-12-16T10:06:07.998834+00:00 | 2024-12-16T10:06:07.998834+00:00 | 408 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code\nTime complexity: $$O(n*k)$$. Space complexity: $$O(n)$$.\n```python3\nclass Solution:\n def getFinalState(self, a: List[int], k: int, q: int) -> List[int]:\n return [setitem(a,a.index(m:=min(a)),m*q) for _ in range(k)] and a\n``` | 4 | 0 | ['Array', 'Simulation', 'Python', 'Python3'] | 1 |
final-array-state-after-k-multiplication-operations-i | C++ Solution || Detailed Explanation | c-solution-detailed-explanation-by-rohit-jjbo | IntuitionThe problem involves modifying elements in a vector based on their values and positions while maintaining an order of operations. Using a priority queu | Rohit_Raj01 | NORMAL | 2024-12-16T08:35:00.850492+00:00 | 2024-12-16T08:35:00.850492+00:00 | 178 | false | # Intuition\nThe problem involves modifying elements in a vector based on their values and positions while maintaining an order of operations. Using a **priority queue (min-heap)** is intuitive here because it allows us to efficiently fetch and update the smallest element at every step, which is critical given the nature of the operation.\n\n# Approach\n1. **Min-Heap Initialization:**\n - Store each element from the array along with its index in a min-heap.\n - This allows us to efficiently retrieve the smallest element and maintain the order of operations.\n\n2. **Iterative Updates:**\n - Perform `k` operations where, in each step:\n - Extract the smallest element from the heap.\n - Multiply its value by the `multiplier`.\n - Push the updated value back into the heap, keeping track of its original index.\n\n3. **Reconstruct the Final Array:**\n - Extract all elements from the heap and place them back in their original positions using the stored indices.\n\n4. **Return the Result:**\n - The resultant array represents the modified state after all operations.\n\n# Complexity\n- **Time Complexity:**\n - Building the heap initially takes $$O(n \\log n)$$.\n - Each of the `k` operations involves a `pop` and a `push` operation, both of which are $$O(\\log n)$$. Thus, the loop takes $$O(k \\log n)$$.\n - Overall complexity: $$O((n + k) \\log n)$$.\n\n- **Space Complexity:**\n - The heap stores all `n` elements, so the space complexity is $$O(n)$$.\n\n# Code\n```cpp\n#include <vector>\n#include <queue>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n int n = nums.size();\n // Min-Heap to store {value, index}\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n\n // Push all elements with their indices into the heap\n for (int i = 0; i < n; i++) {\n pq.push({nums[i], i});\n }\n\n // Perform k operations\n while (k--) {\n auto it = pq.top(); // Smallest element\n pq.pop();\n\n int val = it.first;\n int ind = it.second;\n\n // Update the value and reinsert into the heap\n val *= multiplier;\n pq.push({val, ind});\n }\n\n // Extract final values and reconstruct the array\n vector<int> ans(n, 0);\n while (!pq.empty()) {\n auto it = pq.top();\n pq.pop();\n\n int val = it.first;\n int ind = it.second;\n\n ans[ind] = val;\n }\n\n return ans;\n }\n};\n```\n\n# Example Usage\n```cpp\n#include <iostream>\nusing namespace std;\n\nint main() {\n Solution solution;\n vector<int> nums = {4, 2, 6, 3};\n int k = 3;\n int multiplier = 2;\n\n vector<int> result = solution.getFinalState(nums, k, multiplier);\n\n // Print the result\n for (int num : result) {\n cout << num << " ";\n }\n return 0;\n}\n```\n\n# Explanation of Example\n- **Input:**\n - `nums = [4, 2, 6, 3]`, `k = 3`, `multiplier = 2`\n- **Process:**\n 1. Push all elements into the min-heap with their indices.\n 2. Perform 3 updates on the smallest element each time.\n 3. Reconstruct the array based on the modified values.\n- **Output:**\n - The final array after all operations.\n\n\n\n | 4 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Easy Code || Beginner-friendly || Newbie | easy-code-beginner-friendly-newbie-by-ha-3taw | IntuitionThe problem revolves around repeatedly identifying the smallest number in an array and modifying it in a specified way (x → x * multiplier).Approach
It | HarshitZenith3 | NORMAL | 2024-12-16T04:39:36.366796+00:00 | 2024-12-16T04:39:36.366796+00:00 | 30 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem revolves around repeatedly identifying the smallest number in an array and modifying it in a specified way (x \u2192 x * multiplier).\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate k Times:\n\nEach operation involves scanning the array to identify the minimum value.\n\n2. Find the Minimum Value:\n\nUse min_element to find the smallest value in the array during each operation. This function scans the array and returns an iterator to the first occurrence of the smallest value.\n\n3. Update the Minimum:\n\nOnce the smallest value is identified, loop through the array and multiply all its occurrences by the given multiplier.\n\n4. Return the Final Array:\n\nAfter all k operations, the updated array represents the final state.\n\n# Complexity\n- Time complexity:$$O(K\u2217N)$$\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\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n for (int i = 0; i < k; i++) {\n int minVal = *min_element(nums.begin(), nums.end());\n\n for (int j = 0; j < nums.size(); ++j) {\n if (nums[j] == minVal) {\n nums[j] *= multiplier;\n break;\n }\n }\n }\n return nums;\n }\n};\n\n``` | 4 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.