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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
k-diff-pairs-in-an-array | C++ solution | binary search | sorting | O(n) | c-solution-binary-search-sorting-on-by-r-wxo8 | \nint findPairs(vector<int>& nums, int k)\n{\n sort(nums.begin(), nums.end());\n int count = 0;\n for (int i = 0; i < nums.size(); i++)\n {\n | rajnishgeek | NORMAL | 2021-08-16T12:26:50.888713+00:00 | 2021-08-16T12:26:50.888778+00:00 | 241 | false | ```\nint findPairs(vector<int>& nums, int k)\n{\n sort(nums.begin(), nums.end());\n int count = 0;\n for (int i = 0; i < nums.size(); i++)\n {\n if (i > 0 && i < nums.size() && nums[i - 1] == nums[i])\n {\n while (i < nums.size() && nums[i - 1] == nums[i])\n i++;\n if (i >= nums.size())\n return count;\n }\n int find = k + nums[i];\n int start = i + 1, end = nums.size() - 1;\n while (start <= end)\n {\n int mid = start + (end - start) / 2;\n if (nums[mid] == find)\n {\n count++;\n break;\n }\n else if (find < nums[mid])\n end = mid - 1;\n else\n start = mid + 1;\n }\n\n }\n return count;\n}\n``` | 3 | 3 | ['Binary Search'] | 1 |
k-diff-pairs-in-an-array | C++ O(n) soln | c-on-soln-by-aditya0753-9bx3 | \nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n int n=nums.size();\n unordered_map<int,int> m;\n int c=0;\n | aditya0753 | NORMAL | 2021-08-07T03:28:27.498887+00:00 | 2021-08-07T03:28:27.498915+00:00 | 347 | false | ```\nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n int n=nums.size();\n unordered_map<int,int> m;\n int c=0;\n \n if(k<0) return 0;\n \n for(int i=0;i<n;i++){\n m[nums[i]]++;\n }\n \n if(k==0){\n for(auto x:m){\n if(x.second>1){\n c++;\n }\n }\n return c;\n }\n \n for(auto x:m){\n if(m.count(x.first-k)){\n c++;\n }\n \n }\n return c;\n }\n \n};\n``` | 3 | 0 | [] | 1 |
k-diff-pairs-in-an-array | [C++] Simple single loop approach | c-simple-single-loop-approach-by-ritik30-xyce | \nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n unordered_map<int,int> freq;\n for(int i=0;i<nums.size();i++){\n | ritik307 | NORMAL | 2021-07-14T18:51:44.581141+00:00 | 2021-07-14T18:51:44.581165+00:00 | 504 | false | ```\nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n unordered_map<int,int> freq;\n for(int i=0;i<nums.size();i++){\n freq[nums[i]]++;\n }\n int count=0;\n if(k!=0){\n for(auto itr:freq){\n if(freq.find(itr.first+k)!=freq.end()){\n count++;\n }\n }\n }\n else{\n for(auto itr: freq){\n if(itr.second>1){\n count++;\n }\n }\n }\n return count;\n }\n};\n``` | 3 | 0 | ['Hash Table', 'C', 'C++'] | 0 |
k-diff-pairs-in-an-array | Cpp Solution beats 100% - O(nlogn) Two Pointer Approach [ proof attached ;) ] | cpp-solution-beats-100-onlogn-two-pointe-8c1f | Hello World !!. A two pointer based approach. Code is commented for better understanding. Hope it helps otherwise feel free to comment. \nThanks.\nHappy Coding | zeroAadi | NORMAL | 2021-06-26T08:51:31.623609+00:00 | 2021-07-11T05:21:39.245607+00:00 | 262 | false | Hello World !!. A two pointer based approach. Code is commented for better understanding. Hope it helps otherwise feel free to comment. \nThanks.\nHappy Coding.\n```\n int n=nums.size();\n\t \n\t // Sort the given vector\n sort(nums.begin(),nums.end());\n int i=0;\n int j=1;\n int c=0; // hold the final answer\n int prev=INT_MIN; // keeps tracks of previous element\n while(i<n && j<n){\n\t\t\n if(nums[j]-nums[i] == k)\n {\n c++;\n prev=nums[i]; // Whenever i is going to be incremented we should update the value of prev.\n i++;\n j++;\n }\n\t\t\t// if difference between values of both pointers is more than k, then increment j.\n else if (j<n && nums[j]-nums[i]<k ) j++;\n\t\t\t\n\t\t\t// else increment i\n else{\n prev=nums[i]; // Whenever i is going to be incremented we should update the value of prev.\n i++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Note this while loop carefully. It makes sure that value of current nums[i] is not equal to the previous one, \n\t\t\t\t//because only unique difference pairs should be counted as per problem. So this while loop keep on moving \n\t\t\t\t// until either i becomes equal to n or previous value is not equal to current value.\n while(i<n && nums[i]==prev ) i++;\n\t\t\t\n\t\t\t// It makes sure that both i and j pointers are not pointing to same value. \n\t\t\t// This makes sure to pass the corner cases when k is 0.\n if(i==j) j++;\n }\n return c;\n```\n\n | 3 | 1 | [] | 1 |
k-diff-pairs-in-an-array | Easy C++ Soln || nlogn || One pointer with Binary Search | easy-c-soln-nlogn-one-pointer-with-binar-x5um | \nclass Solution {\npublic:\n //one pointer with binary search nlogn\n int findPairs(vector<int>& nums, int k) {\n int ans=0;\n sort(nums.be | mitedyna | NORMAL | 2021-05-24T21:58:46.854304+00:00 | 2021-05-24T21:58:46.854334+00:00 | 292 | false | ```\nclass Solution {\npublic:\n //one pointer with binary search nlogn\n int findPairs(vector<int>& nums, int k) {\n int ans=0;\n sort(nums.begin(),nums.end());\n for(int i=0;i<nums.size()-1;i++){\n if(i>0 && nums[i]==nums[i-1])continue;\n int x=nums[i];\n int l=i+1,r=nums.size()-1;\n while(l<=r){\n int m=(l+r)>>1;\n if(nums[m]-x==k){\n ans++;\n break;\n }\n else if(nums[m]-x>k)r=m-1;\n else l=m+1;\n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['C', 'Binary Tree'] | 0 |
k-diff-pairs-in-an-array | C++ || Simple easy solution || Two pointer technique | c-simple-easy-solution-two-pointer-techn-m5tz | \nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n int count | akanksha_06 | NORMAL | 2021-05-23T07:42:20.244377+00:00 | 2021-05-23T07:42:20.244425+00:00 | 214 | false | ```\nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n int count=0;\n int i=0;\n int j=1;\n while(i<n && j<n)\n {\n if(i!=j && nums[j]-nums[i]==k){\n while(i+1 < n && nums[i+1] == nums[i]) // to check for distinct pairs\n i++;\n i++;\n while(j+1<n && nums[j+1] == nums[j]) //to check for distinct pairs\n j++;\n j++;\n count++;\n }\n else if(nums[j]-nums[i]<k) j++;\n else i++;\n }\n return count;\n }\n};\n```\n | 3 | 1 | ['Two Pointers', 'C'] | 0 |
k-diff-pairs-in-an-array | C++ solution using set and hashmap. TC - O(nlogn) and SC - O(n) | c-solution-using-set-and-hashmap-tc-onlo-wdbw | \nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n unordered_map<int,int> mp;\n \n int s = nums.size();\n | sumit_code | NORMAL | 2021-04-17T04:38:21.912573+00:00 | 2021-04-17T04:38:21.912604+00:00 | 365 | false | ```\nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n unordered_map<int,int> mp;\n \n int s = nums.size();\n \n for(int i=0;i<s;i++)\n mp[nums[i]] = i;\n \n \n int res = 0;\n \n set<pair<int,int>> st;\n \n for(int i=0;i<s;i++) {\n int d = nums[i]-k;\n \n if(mp.find(d)!=mp.end() && i!=mp[d])\n st.insert({nums[i],d});\n \n }\n \n return st.size();\n }\n};\n``` | 3 | 1 | ['C', 'Ordered Set'] | 1 |
minimum-deletions-to-make-string-k-special | [Java/C++/Python] Enumerate Minimum Frequency | javacpython-enumerate-minimum-frequency-038ab | Intuition\nFirst, we need to calculate character frequencies.\nwe delete characters for two reasons:\n1. Delete the small frequency to zero, so it doesn\'t coun | lee215 | NORMAL | 2024-03-17T04:09:32.411228+00:00 | 2024-03-17T07:38:17.504122+00:00 | 3,176 | false | # **Intuition**\nFirst, we need to calculate character frequencies.\nwe delete characters for two reasons:\n1. Delete the small frequency to zero, so it doesn\'t count for the rule.\n2. Delete the big frequency smaller, so it `big freq - small freq <= k`.\nAnd we won\'t reduce small freq to smaller positive.\n<br>\n\n# **Intuition 2**\nAfter deletion,\nthe char with the minimum frequency,\nmust not have been deleted,\nit\'s same as its original frequency in `word`.\n<br>\n\n# **Explanation**\n\nEnumerate character\'s frequency `x`\nThe goal is to find the minimum deletions needed,\nif we take it as the minimum frequency after deletion.\n\nThen we iterates over all character frequencies `a`,\nit calculates the deletions required to meet the k-special condition:\nIf `a < x`, all instances of that character need to be deleted.\nIf `a > x + k`, then `a - (x + k)` deletions are needed.\nUpdate this to current result `cur`.\n\nFinally return the minimum result we found.\n<br>\n\n# **Complexity**\nTime `O(n + 26 * 26)`\nSpace `O(26)`\n<br>\n\n**Java**\n```java\n public int minimumDeletions(String word, int k) {\n int res = 100000, A[] = new int[26];\n for (char c : word.toCharArray()) {\n A[c - \'a\']++;\n }\n for (int x : A) {\n int cur = 0;\n for (int a : A) {\n cur += (a < x) ? a : Math.max(0, a - (x + k));\n }\n res = Math.min(res, cur);\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n int minimumDeletions(string word, int k) {\n vector<int> A(26);\n for (char& c : word) {\n A[c - \'a\']++;\n }\n int res = 1e6;\n for (int x : A) {\n int cur = 0;\n for (int a : A) {\n cur += (a < x) ? a : max(0, a - (x + k));\n }\n res = min(res, cur);\n }\n return res;\n }\n```\n\n**Python**\n```py\n def minimumDeletions(self, word: str, k: int) -> int:\n A = Counter(word).values()\n res = inf\n for x in A:\n cur = 0\n for a in A:\n cur += a if a < x else max(0, a - (x + k))\n res = min(res, cur)\n return res\n```\n | 57 | 1 | ['C', 'Python', 'Java'] | 18 |
minimum-deletions-to-make-string-k-special | Explained - using simple freq check | explained-using-simple-freq-check-by-kre-kh7f | Approach\n- Find the frequency of each of the characters in word\n- Sort the freq array\n- Consider each of the freq as the minFreq possible and with this consi | kreakEmp | NORMAL | 2024-03-17T04:02:18.060816+00:00 | 2024-03-17T05:09:08.157531+00:00 | 5,706 | false | # Approach\n- Find the frequency of each of the characters in word\n- Sort the freq array\n- Consider each of the freq as the minFreq possible and with this consideration we need to evaluate how many char from the higher frequency to be deleted to get the condition satisfied for all freq\n- Consider the next frequency as min and collect all lower freq count as deleted one and then again evaluate the hiher side freq deletion\n\n# Code\n```\nint minimumDeletions(string word, int k) {\n vector<int> freq(26, 0);\n int deleted = 0, ans = word.size();\n for(auto c: word) freq[c-\'a\']++; // find frequency of each chars\n sort(freq.begin(), freq.end()); // sort the freq array\n for(int i = 0; i < freq.size(); ++i){ // Iterate over freq \n int res = deleted, minFreq = freq[i]; // consider the current freq as the min freq after deletion. Also add the already deleted freq to temporary result\n for(int j = freq.size()-1; j > i; --j){ // iterate over freq array to evaluate the chars to be deleted from the higher freq side of the freq array\n if(freq[j] - minFreq <= k) break; // Once condition is satisfied then exit from the loop\n res += freq[j] - minFreq - k; // accumulate on the result - number of items to be deleted\n }\n ans = min(ans, res); // keep tracking the min possible value\n deleted += freq[i]; // update the deleted freq with current freq\n }\n return ans;\n}\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--- | 34 | 0 | ['C++'] | 9 |
minimum-deletions-to-make-string-k-special | Simple Hashing || Consider All Possibilities | simple-hashing-consider-all-possibilitie-ws58 | # Intuition \n\n\n# Approach\n1. Initialize an unordered map mp to store the frequency of each character in the word.\n2. Iterate through the characters in th | AdityaRaj_cpp | NORMAL | 2024-03-17T04:02:01.092233+00:00 | 2024-03-17T04:02:01.092261+00:00 | 2,990 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize an unordered map mp to store the frequency of each character in the word.\n2. Iterate through the characters in the word and update the frequency in the map.\n3. Create a vector v to store the frequencies of characters.\n4. Sort the frequencies in ascending order.\n5. Find the maximum frequency among all characters.\n6. Iterate from 1 to the maximum frequency (mx).\n7. For each frequency i, calculate the total number of deletions required to make all frequencies equal to i or at most i + k.\n8. Update the minimum number of deletions (ans) encountered so far.\n9. Return the minimum number of deletions.\n\n# Code\n```\nclass Solution\n{\npublic:\n int minimumDeletions(string word, int k)\n {\n unordered_map<char, int> mp;\n int n = word.size();\n for (char ch : word)\n mp[ch]++;\n vector<int> freq;\n for (auto x : mp)\n freq.push_back(x.second);\n sort(freq.begin(), freq.end());\n int mx = freq.back(), ans = INT_MAX;\n for (int i = 1; i <= mx; i++)\n {\n int cnt = 0;\n for (int j = 0; j < freq.size(); j++)\n {\n if (freq[j] > i + k)\n cnt += freq[j] - i - k;\n else if (freq[j] < i)\n cnt += freq[j];\n }\n ans = min(ans, cnt);\n }\n return ans;\n }\n};\n``` | 29 | 1 | ['Hash Table', 'Sorting', 'C++'] | 7 |
minimum-deletions-to-make-string-k-special | C++||With explanation | cwith-explanation-by-baibhavkr143-w5sc | 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 | baibhavkr143 | NORMAL | 2024-03-17T04:00:46.049068+00:00 | 2024-03-17T04:07:15.792122+00:00 | 1,532 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int solve(int minV,vector<int>&arr,int k)//Range=[minV,minV+k]\n {\n int ans=0;\n for(int i=0;i<arr.size();i++)\n {\n if(arr[i]<minV)\n {\n ans+=arr[i];\n continue;\n }\n if(arr[i]>minV+k)\n {\n ans+=arr[i]-(minV+k);\n }\n }\n return ans;\n \n }\n int minimumDeletions(string word, int k) {\n //Main point here is we have onlly 26 unique elements\n //Whenever question says that diff between any two element is less than or eqal to k it means all values must be in some range\n // if k==0 means all value should be equal\n // if k=1 means only two values are allowed which is consecutive \n // k=2 means three values are allowed which is consecutive\n // so if we fix smallest value then we will know the range will be from [smallest_value,smallest_value+k];\n vector<int>freq(26,0);\n for(auto it:word)freq[it-\'a\']++;\n \n vector<int>arr;\n for(int i=0;i<26;i++)\n {\n if(freq[i])arr.push_back(freq[i]);\n }\n sort(arr.begin(),arr.end());\n int ans=1e9;\n for(int i=0;i<=arr.back();i++)//selecting minV\n {\n ans=min(ans,solve(i,arr,k)); \n }\n return ans;\n \n }\n};\n``` | 15 | 1 | ['C++'] | 4 |
minimum-deletions-to-make-string-k-special | Simple java solution | simple-java-solution-by-siddhant_1602-nps2 | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public int minimumDeletions(String word, int k) {\n in | Siddhant_1602 | NORMAL | 2024-03-17T04:02:39.059413+00:00 | 2024-03-17T04:02:39.059446+00:00 | 816 | false | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int a[]=new int[26];\n for(char c:word.toCharArray())\n {\n a[c-\'a\']++;\n }\n Arrays.sort(a);\n List<Integer> nm = new ArrayList<>();\n for(int i=25;i>=0;i--)\n {\n if(a[i] == 0)\n {\n break;\n }\n else\n {\n nm.add(a[i]);\n }\n }\n int ans = Integer.MAX_VALUE;\n for(int i=0;i<nm.size();i++)\n {\n int data=nm.get(i);\n int min=0;\n for(int j:nm)\n {\n if(j>(data + k))\n {\n min += j-(data + k);\n }\n else if(j<data)\n {\n min += j;\n }\n }\n ans=Math.min(ans, min);\n if(ans == 0)\n {\n break;\n }\n }\n return ans == Integer.MAX_VALUE ? 0 : ans; \n }\n}\n``` | 14 | 0 | ['Java'] | 1 |
minimum-deletions-to-make-string-k-special | Python 3 || 7 lines, Counter || T/S: 98% / 29% | python-3-7-lines-counter-ts-98-29-by-spa-s5dn | Here\'s the plan:\n\n\n1. We use Counter to determine the counts of the characters as the list vals.\n\n1. We construct a function minimumDeletions that, given | Spaulding_ | NORMAL | 2024-03-17T20:07:49.067850+00:00 | 2024-05-24T20:15:43.657009+00:00 | 313 | false | Here\'s the plan:\n\n\n1. We use `Counter` to determine the counts of the characters as the list `vals`.\n\n1. We construct a function `minimumDeletions` that, given a range [*num... num+k*], determines the minimum count of deletions to ensure that character counts remaining after these deletions are in that interval.\n\n1. We evaluate the function for each element in `vals` and return the the minimum result. \n\n\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n\n def deletions(num: int, res = 0)-> int:\n\n for v in vals:\n if v < num: res+= v\n if v > num+k: res+= v - num- k\n\n return res \n \n\n vals = Counter(word).values()\n \n return min(map (deletions,vals))\n```\n[https://leetcode.com/problems/minimum-deletions-to-make-string-k-special/submissions/1206582720/](https://leetcode.com/problems/find-trending-hashtags/submissions/1206775504/)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(word)`. (Recall `len(vals.keys())` <= 26) | 9 | 0 | ['Python3'] | 2 |
minimum-deletions-to-make-string-k-special | Easy C++ Solution using Dynamic Programming and Sorting | easy-c-solution-using-dynamic-programmin-gavh | Intuition\nThe problem requires finding the minimum number of characters needed to delete from a string to make it k-special. A string is considered k-special i | vanshwari | NORMAL | 2024-03-17T04:03:17.198623+00:00 | 2024-04-03T05:51:53.683977+00:00 | 549 | false | # Intuition\nThe problem requires finding the minimum number of characters needed to delete from a string to make it k-special. A string is considered k-special if the absolute difference in frequencies of any two characters in the string is less than or equal to k.\n\n# Approach\n1. Count the frequencies of each character in the string `word`.\n2. Sort the frequencies in ascending order.\n3. Use dynamic programming to find the minimum number of characters needed to delete to make the substring k-special.\n4. If the absolute difference between frequencies of characters at indices `i` and `j` is less than or equal to `k`, no characters need to be deleted.\n5. Otherwise, calculate the number of characters needed to delete to make the substring k-special.\n6. Return the minimum number of characters needed to delete.\n\n# Complexity\n- Time complexity: O(N) as we are traversing the string.\n- Space complexity: O(26^2) = O(1) since the DP table has a fixed size and additional space is used for storing intermediate results, which doesn\'t scale with the input size.\n\n# Code\n```cpp\nclass Solution {\npublic:\n // Helper function to recursively solve the problem using dynamic programming\n int minDeletions(int i, int j, int A[], int k, vector<vector<int>>& dp) {\n // Base case: If the range [i, j] is empty or has only one element,\n // no characters need to be deleted, so return 0.\n if (i >= j) return 0;\n \n // If the frequency of the character at index i is zero, skip it.\n if (A[i] == 0) return minDeletions(i + 1, j, A, k, dp);\n \n // If the absolute difference between frequencies of characters at indices i and j\n // is less than or equal to k, no characters need to be deleted, so return 0.\n if (A[j] - A[i] <= k) return 0;\n \n // If the result for the current range [i, j] is already calculated, return it.\n if (dp[i][j] != -1) return dp[i][j];\n \n // Calculate the number of characters needed to delete to make the substring k-special.\n // Two options:\n // 1. Delete characters from the left side of the substring.\n // 2. Delete characters from the right side of the substring.\n int takeLeft = A[i] + minDeletions(i + 1, j, A, k, dp);\n int takeRight = A[j] - A[i] - k + minDeletions(i, j - 1, A, k, dp);\n \n // Store the minimum number of characters needed to delete for the current range [i, j].\n dp[i][j] = min(takeLeft, takeRight);\n \n // Return the minimum number of characters needed to delete for the current range [i, j].\n return dp[i][j];\n }\n \n // Main function to find the minimum number of characters to delete\n int minimumDeletions(string word, int k) {\n // Array to store the frequencies of characters\n int A[26] = {0};\n // Count the frequencies of characters in the word\n for (char ch : word) {\n A[ch - \'a\']++;\n }\n // Sort the frequencies in ascending order\n sort(A, A + 26);\n \n // Initialize the indices i and j\n int i = 0, j = 25;\n \n // Initialize the DP table with -1 (indicating that the result is not calculated yet)\n vector<vector<int>> dp(26, vector<int>(26, -1));\n \n // Call the helper function to solve the problem\n return minDeletions(i, j, A, k, dp);\n }\n};\n``` | 9 | 0 | ['C++'] | 1 |
minimum-deletions-to-make-string-k-special | C++ 100% Faster | Easy Step By Step Explanation | c-100-faster-easy-step-by-step-explanati-brnt | Intuition\nThe key to solve this problem lies in identifying the discrepancies between character frequencies. A string is k-special if the absolute difference b | VYOM_GOYAL | NORMAL | 2024-03-17T04:00:46.362211+00:00 | 2024-03-18T01:39:33.640927+00:00 | 860 | false | # Intuition\nThe key to solve this problem lies in identifying the discrepancies between character frequencies. A string is k-special if the absolute difference between the frequencies of any two characters (|freq(i) - freq(j)|) is less than or equal to k. Therefore, we need to find the minimum number of deletions required to minimize these frequency differences.\n\n# Approach\n1. **Character Frequency Count:**\n - Create a hash table (unordered_map) to store the frequency of each character in the string (word).\n - Iterate through the string and update the corresponding character\'s count in the hash table.\n2. **Frequency Array and Sorting:**\n - Extract the character frequencies from the hash table and store them in a separate vector (freq).\n - Sort the frequency vector (freq) in descending order. This ensures we focus on characters with the highest frequencies first, as they potentially contribute to the most deletions.\n3. **Iterative Comparison:**\n - Initialize a variable ans to store the minimum number of deletions (initially set to positive infinity).\n - **Iterate through the sorted frequency vector (freq):**\n - **For each frequency num in freq:**\n - Initialize a counter cnt to track the number of deletions needed for the current frequency.\n - **Iterate through the entire frequency vector again:**\n - **If the difference between the current frequency (num) and another frequency (freq[j]) is greater than k (freq[j] - num > k):**\n - This indicates a violation of the k-special condition. We need to delete characters with frequency freq[j] down to num + k. Calculate the number of deletions by subtracting the allowed frequency (num + k) from the actual frequency (freq[j]).\n - **If the current frequency (num) is higher than another frequency (freq[j]): (num > freq[j])**\n - This also violates the k-special condition because characters with lower frequency cannot exceed the allowed difference. We need to delete all characters with frequency freq[j].\n - Update cnt with the total number of deletions calculated for the current frequency (num).\n - Update ans with the minimum number of deletions encountered so far (ans = min(ans, cnt)).\n - If cnt is zero (no deletions needed), stop iterating further as we\'ve found a solution where the current frequency doesn\'t require any deletions.\n4. **Return Minimum Deletions:**\n - After iterating through all frequencies, return the minimum number of deletions found (ans).\n\n# Complexity\n- Time complexity: **O(26*26)** \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#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<char, int> mp;\n for (auto it : word) {\n mp[it]++;\n }\n\n vector<int> freq;\n for (auto it : mp) {\n freq.push_back(it.second);\n }\n sort(freq.begin(), freq.end(), greater<int>());\n\n int ans = INT_MAX; \n\n for (int i = 0; i < freq.size(); i++) {\n int num = freq[i]; \n int cnt = 0;\n\n for (int j = 0; j < freq.size(); j++) {\n if (freq[j] - num > k) {\n cnt += freq[j] - (num + k);\n } \n else if (num > freq[j]) {\n cnt += freq[j];\n }\n }\n ans = min(ans, cnt);\n if (cnt == 0) {\n break;\n }\n }\n\n return ans;\n }\n};\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n\n | 8 | 1 | ['Array', 'Math', 'C++'] | 2 |
minimum-deletions-to-make-string-k-special | Python Easy Solution | python-easy-solution-by-shree_govind_jee-y5l6 | Code\nJava\n\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int[] freq = new int[26];\n for(char ch:word.toCharArray() | Shree_Govind_Jee | NORMAL | 2024-03-17T04:04:20.333307+00:00 | 2024-03-17T04:04:20.333335+00:00 | 781 | false | # Code\n**Java**\n```\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int[] freq = new int[26];\n for(char ch:word.toCharArray()){\n freq[ch-\'a\']++;\n }\n \n// Sorted in Increasing order\n Arrays.sort(freq);\n int min_del = Integer.MAX_VALUE;\n \n for(int i=freq.length-1; i>=0; i--){\n int trgt = freq[i];\n int dels = 0;\n \n for(int f:freq){\n if(f > trgt + k){\n dels += f - (trgt+k); \n } else if(f < trgt){\n dels += f;\n }\n }\n \n min_del = Math.min(min_del, dels);\n if(min_del == 0){\n break;\n }\n }\n \n return min_del==Integer.MAX_VALUE?0:min_del;\n }\n}\n```\n**Python**\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n freq = {}\n for char in word:\n freq[char] = freq.get(char, 0)+1\n \n \n frequencies = sorted(freq.values(), reverse=True)\n min_del = float(\'inf\')\n \n for i in range(len(frequencies)):\n trgt = frequencies[i]\n dels = 0\n for f in frequencies:\n if f>trgt+k:\n dels += f - (trgt+k)\n elif f < trgt:\n dels += f\n min_del = min(min_del, dels)\n if min_del == 0:\n break\n \n return min_del if min_del != float(\'inf\') else 0\n``` | 7 | 0 | ['Array', 'Python', 'Python3'] | 3 |
minimum-deletions-to-make-string-k-special | Dynamic Programming Easy to Understand Solution | dynamic-programming-easy-to-understand-s-tmj7 | Intuition\nThe function f is recursively called to find the minimum number of deletions required. It considers the leftmost and rightmost characters \nIf the di | asitvts | NORMAL | 2024-03-17T04:30:14.007159+00:00 | 2024-03-17T04:30:14.007177+00:00 | 390 | false | # Intuition\nThe function f is recursively called to find the minimum number of deletions required. It considers the leftmost and rightmost characters \nIf the difference between their frequencies is less equal to k, no need to check further.\nElse perform deletion\nDeletion can be done in two different ways\n- Either delete the lower frequency element\n- Or remove required appearances from higher frequency element\n\n# Approach\n- Count frequency of every character and store in array\n- Sort this array\n- Call the function\n\n# Complexity\n- Time complexity:\n**O(N^2)** again n is just 26\n\n- Space complexity:\n**O(26) = O(1)**\n\n# Code\n```\nclass Solution {\nprivate:\n int dp[26][26];\n int f(vector<int>&freq, int l, int r, int k){\n if(l==r)return 0;\n if(freq[r]-freq[l]<=k)return 0;\n if(dp[l][r]!=-1)return dp[l][r];\n \n return dp[l][r]=min(freq[l]+f(freq,l+1,r,k), freq[r]-(freq[l]+k)+f(freq,l,r-1,k));\n }\npublic:\n int minimumDeletions(string word, int k) {\n vector<int>freq(26,0);\n for(int i=0; i<word.size(); i++){\n freq[word[i]-\'a\']++;\n }\n sort(freq.begin(),freq.end());\n memset(dp,-1,sizeof(dp));\n return f(freq,0,25,k);\n }\n};\n``` | 6 | 0 | ['Dynamic Programming', 'Sorting', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | Easy to Understand O(N) TC and O(1) SC Beats 100% | easy-to-understand-on-tc-and-o1-sc-beats-yogf | https://leetcode.com/problems/minimum-deletions-to-make-string-k-special/submissions/1206029598/\n# Intuition\n Describe your first thoughts on how to solve thi | sainadth | NORMAL | 2024-03-17T06:13:53.920826+00:00 | 2024-03-17T10:51:27.294504+00:00 | 283 | false | [https://leetcode.com/problems/minimum-deletions-to-make-string-k-special/submissions/1206029598/]()\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntution is to select a non zero frequency and make all the other frequencies to be in the range of `[frequency, frequency + k]`\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSee psuedo code in comments\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n /* \n 1. calculate the character frequency\n 2. Intution is to select a non zero frequency(freqSelected) and make all the other to be in the [freqSelected, freqSelected + k]\n a. if freq[i] < freqSelected => you can\'t select freq[i] so add to cost\n b. if freqSelected <= freq[i] <= freqSelected + k => aleady in the range no additional cost required\n c. if freqSelected > freq[i] + k => minimum cost is to set freq[i] = freqSelected + k\n E.g freqSelected = 5, k = 4\n 1 2 3 4 5 6 7 8 9 10\n 1 < 5 => cost = 1\n 2 < 5 => cost = 1 + 2 = 3\n 3 < 5 => cost = 3 + 3 = 6\n 4 < 5 => cost = 6 + 4 = 10\n 5 belongs to [5, 9] => cost = 10 // already in range\n 6 belongs to [5, 9] => cost = 10 // already in range\n 7 belongs to [5, 9] => cost = 10 // already in range\n 8 belongs to [5, 9] => cost = 10 // already in range\n 9 belongs to [5, 9] => cost = 10 // already in range\n 10 > (5 + 4) => cost = 10 + (10 - (5 + 4)) = 10 + 1 = 11\n 3. repeat step2 for all non-zero frequencies\n 4. return minimum cost calculated\n\n TC - O(N) + O(26 * 26) = O(N) where N is length of string\n SC - O(1) since fq vector is of constant space\n */\n /* Count frequency of character in word (a-z) */\n vector<int> fq(26, 0);\n for(auto i : word) fq[i - \'a\']++;\n int miny = INT_MAX;\n for(int i = 0; i < 26; i++){\n int c = 0;\n if(fq[i] == 0) continue;\n /* freqSelected is fq[i] */\n for(int j = 0; j < 26; j++){\n if(fq[j] < fq[i]) c += fq[j]; /* fq[j] < freqSelected */\n else if(fq[j] - fq[i] <= k) continue; /* freqSelected <= fq[j] <= freqSelected + k */\n else c += fq[j] - fq[i] - k; /* fq[j] > freqSelected + k */\n }\n miny = min(miny, c);\n }\n return miny;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
minimum-deletions-to-make-string-k-special | [Python3] DFS + Backtracking | python3-dfs-backtracking-by-dolong2110-xtre | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dolong2110 | NORMAL | 2024-03-17T04:05:05.493830+00:00 | 2024-03-17T14:57:55.505353+00:00 | 311 | 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##### 1.\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n c = collections.Counter(word)\n cnt = sorted(collections.Counter(word).values())\n res = 0\n \n def helper(i: int, j: int) -> int:\n if i >= j: return 0\n if cnt[j] - cnt[i] <= k: return 0\n res = float("inf")\n ci = cnt[i]\n cnt[i] = 0\n res = min(res, helper(i + 1, j) + ci)\n cnt[i] = ci\n \n cj = cnt[j]\n cnt[j] = cnt[i] + k\n if cnt[j] == 0:\n res = min(res, helper(i, j - 1) + cj)\n else:\n res = min(res, helper(i, j - 1) + cj - cnt[j])\n cnt[j] = cj\n return res\n \n return helper(0, len(cnt) - 1)\n```\n\n##### 2. \n\nInspired by lee215\n\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n cnt = collections.Counter(word).values()\n res = float("inf")\n for x in cnt:\n res = min(res, sum(c if c < x else max(0, c - x -k) for c in cnt))\n return res\n``` | 5 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | Simple C++ solution, very intuitive | simple-c-solution-very-intuitive-by-fell-hfpr | Intuition\n Describe your first thoughts on how to solve this problem. \nAt the beginning the problem seems a little bit scary, infact it tells us to consider a | Felle33 | NORMAL | 2024-03-17T20:24:25.951043+00:00 | 2024-03-17T20:25:39.717850+00:00 | 316 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt the beginning the problem seems a little bit scary, infact it tells us to consider all the pairwise indeces and confront them.\nIn reality we don\'t have to confront all the possible indeces, but just the letters.\n\n**The main intuition** is to transform the problem from a "confront all the letters in the indeces" problem to a "count the letters and confront the frequencies" problem.\nNow we don\'t care anymore about the letters, but we care about their frequencies and the fact that the difference between the minimum and the maximum frequencies must not be above $$k$$.\n\n**The last step** to conclude the problem is the following: we can $$delete$$ all the characters of the same type or $$reduce$$ them to enter the interval between the minimum and the maximum frequencies.\nIn order to do that I try every single frequency to be the minimum and then calculate how the others can enter the interval and when I pass from a frequency to another, it is like deleting all the characters of the first frequency because now they cannot be in the interval anymore.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst of all I have counted all the letters and stored in a vector, then I sorted it in increasing order.\nAt this point I have initialized the variable $$ans$$ (the answer of the problem) to infinite and $$startDel$$ as 0.\nAt each iteration the current deleted elements $$curDel$$ is initialized with the already deleted characters ($$startDel$$) then I try to reduce the other characters to enter the interval represented by $$[cnt[i], cnt[i] + k]$$, so when a frequency is outside the limit a deletion is needed.\nAt the end of the iteration I update the answer and the $$startDel$$ characters because I have to pass to the next iteration.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ with n = length of the string\nBecause to read all the string I use $$O(n)$$ time, but then all the other operations are constant because they are operating on constant numbers\n\n- Space complexity:\n$$O(1)$$ it is constant because I have always to allocate a vector of 26 elements\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int> cnt(26);\n \n for(char c : word) {\n cnt[c - \'a\']++;\n }\n \n sort(cnt.begin(), cnt.end());\n int ans = 1e9;\n int startDel = 0;\n \n for(int i = 0; i < 26; i++) {\n int curDel = startDel;\n int topLimit = cnt[i] + k;\n for(int j = i + 1; j < 26; j++) {\n if(topLimit < cnt[j]) curDel += cnt[j] - topLimit;\n }\n ans = min(ans, curDel);\n startDel += cnt[i];\n }\n \n return ans;\n }\n};\n``` | 4 | 0 | ['String', 'Greedy', 'C++'] | 1 |
minimum-deletions-to-make-string-k-special | Short explanation + Comments || 87ms Solution || Using 2-Dimensional DP || O(N) time and O(1) space | short-explanation-comments-87ms-solution-mw95 | Approach\n Describe your approach to solving the problem. \nFirst, calculate frequencies of all the characters.\n\nObservation - For each pair of indices in the | neil_paul | NORMAL | 2024-03-17T06:45:19.936798+00:00 | 2024-03-17T06:47:00.336053+00:00 | 146 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, calculate frequencies of all the characters.\n\nObservation - For each pair of indices in the frequency array, we can either delete all characters of the lower frequency, or reduce just enough characters of the higher frequency as to make their difference = k. \nTo optimise the solution, we can first sort the frequencies and use two pointers `i` and `j` that begin from outside and move in. We can be assured that as soon as we reach the pair of indices whose difference is less than or equal to `k`, all other pairs of indices `p` and `q`, where `i <= p,q <= j `, their difference will be less than k.\n\nSince for each operation, we have two options, either of which can yield correct results, DP can prove to be an effective way to go with.\n\n# Complexity\n- Time complexity: O(N)\nO(N) to calculate frequency + O(C) to sort + O(C) for the memoization logic, where C = number of distinct characters (which can be 26 at max) and N = size of the input string.\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(1)\nO(26) to store frequency + O(26) for recursive stack.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n d = Counter(word)\n self.memo = {}\n freq = sorted(list(d.values())) #sort frequencies\n return self.f(0,len(freq)-1, k, freq)\n\n def f(self, i, j, k, freq):\n #if the difference between max and min frequencies <= k, then all frequencies would be at most k distance apart.\n if abs(freq[i] - freq[j]) <= k: \n return 0\n\n if (i,j) not in self.memo:\n a = b = float(\'inf\')\n a = freq[i] + self.f(i+1, j,k, freq) #either delete all characters of smaller frequency\n b = freq[j] - freq[i] - k + self.f(i,j-1,k,freq) #or remove just enough characters of higher frequency as to make difference = k\n #shift edges i or j accordingly\n self.memo[(i,j)] = min(a,b) #memoize the result for future.\n return self.memo[(i,j)]\n \n \n```\n\n# If you made this far, might as well drop a like :D | 4 | 0 | ['Python3'] | 2 |
minimum-deletions-to-make-string-k-special | Binary Search || Prefix Sum || nlog(n) solution || Iterate over all possible values as the minimum | binary-search-prefix-sum-nlogn-solution-gm8u8 | Intuition\n Describe your first thoughts on how to solve this problem. \n\nAfter computing the frequency of characters in the string, we can convert the problem | hliu4 | NORMAL | 2024-03-17T04:24:43.097857+00:00 | 2024-03-17T23:18:50.275409+00:00 | 434 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nAfter computing the frequency of characters in the string, we can convert the problem to the following:\n\nGiven an array nums and an integer k, find the minimum number of operations to make |nums[i] - nums[j]| <= k for any pair of i and j.\n\nThe intuition is to traverse over all possible values of nums[i] being the minimum and find the min ops. A brute force solution will take o(n) calculate ops for any given nums[i], bring the total time complexity to o(n^2). We can use binary search and prefix sum to make the operation o(log(n)).\n\nAfter sorting nums, for any given nums[i], we have to delete all values on its left, meaning ops_left = sum[0, i -1]. Then we use binary search to find the first element at idx j bigger than nums[i] + k. ops_right = sum[j:n-1] - count[j:n-1]*(nums[i] + k).\n\n# Code\n```\nclass Solution {\n public int bs(int[] freqs, int i, int target){\n int l = -1;\n int r = freqs.length;\n l = i;\n while(l < r){\n int mid = (l + r)/2;\n if(freqs[mid] > target){\n r = mid;\n }else{\n l = mid + 1;\n }\n }\n return r;\n }\n\n public int findOps(int[] freqs, int k){\n\n int ans = Integer.MAX_VALUE;\n int[] prefix = new int[freqs.length + 1];\n prefix[0] = 0;\n int sum = 0;\n for(int i = 0; i < freqs.length; i++){\n sum += freqs[i];\n prefix[i+1] = sum;\n }\n\n for(int i = 0; i < freqs.length; i++){ \n int curr = 0;\n int target = freqs[i] + k;\n int idx = bs(freqs, i, target);\n int cnt = freqs.length - idx;\n int right_sum = prefix[freqs.length] - prefix[idx];\n curr += (right_sum - cnt*target);\n curr += prefix[i];\n ans = Math.min(ans, curr);\n }\n\n return ans;\n }\n \n public int minimumDeletions(String word, int k) {\n int[] freqs = new int[26];\n for(int i = 0; i < word.length(); i++){\n char c = word.charAt(i);\n freqs[c - \'a\']++;\n }\n \n Arrays.sort(freqs);\n int ans = findOps(freqs, k);\n return ans;\n }\n}\n``` | 4 | 0 | ['Binary Search', 'Prefix Sum', 'Java'] | 0 |
minimum-deletions-to-make-string-k-special | Java Clean Solution || Weekly Contest | java-clean-solution-weekly-contest-by-sh-flki | Complexity\n- Time complexity:O(n+Soting + 26*26)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(26)\n Add your space complexity here, e.g. | Shree_Govind_Jee | NORMAL | 2024-03-17T04:03:03.470518+00:00 | 2024-03-17T04:03:03.470561+00:00 | 454 | false | # Complexity\n- Time complexity:$$O(n+Soting + 26*26)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(26)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int[] freq = new int[26];\n for(char ch:word.toCharArray()){\n freq[ch-\'a\']++;\n }\n \n// Sorted in Increasing order\n Arrays.sort(freq);\n int min_del = Integer.MAX_VALUE;\n \n for(int i=freq.length-1; i>=0; i--){\n int trgt = freq[i];\n int dels = 0;\n \n for(int f:freq){\n if(f > trgt + k){\n dels += f - (trgt+k); \n } else if(f < trgt){\n dels += f;\n }\n }\n \n min_del = Math.min(min_del, dels);\n if(min_del == 0){\n break;\n }\n }\n \n return min_del==Integer.MAX_VALUE?0:min_del;\n }\n}\n``` | 4 | 0 | ['Array', 'Python', 'Java', 'Python3'] | 2 |
minimum-deletions-to-make-string-k-special | Beats 💯% of all other | Beginner Friendly✅ | beats-of-all-other-beginner-friendly-by-0gexr | Intuition\n\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n- Create a freq map for every charecter\n- Sort the value of each cha | viresh_dev | NORMAL | 2024-03-17T05:22:50.420348+00:00 | 2024-03-17T05:22:50.420382+00:00 | 180 | false | # Intuition\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Create a freq map for every charecter\n- Sort the value of each charecter\n- check for every charecter\n - if we take the charecter\n - else we are removing all occurence of the charecter\n- find the min of all\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n freq = Counter(word)\n mp=sorted(freq.values())\n\n ans=float("inf")\n for i in range(len(mp)):\n mn=mp[i]\n res=sum(mp[:i])\n for j in range(i,len(mp)):\n if mp[j] - mn>k:\n res+=(mp[j] - mn)-k\n ans=min(ans,res)\n return ans\n``` | 3 | 0 | ['Array', 'Hash Table', 'Greedy', 'Sorting', 'Python3'] | 2 |
minimum-deletions-to-make-string-k-special | Easy Java Solution | easy-java-solution-by-mayur0106-oyas | \n# Code\n\n\nclass Solution {\n public int minimumDeletions(String word, int k) {\n \n // store the frequency of the character\n Intege | mayur0106 | NORMAL | 2024-03-17T04:14:43.765684+00:00 | 2024-03-17T04:14:43.765712+00:00 | 249 | false | \n# Code\n```\n\nclass Solution {\n public int minimumDeletions(String word, int k) {\n \n // store the frequency of the character\n Integer []arr=new Integer[26];\n for(int i=0;i<arr.length;i++) {\n arr[i]=0;\n }\n for(int i=0;i<word.length();i++)\n {\n arr[word.charAt(i)-\'a\']++;\n }\n \n // sort the array in reverse order\n Arrays.sort(arr,Collections.reverseOrder());\n // System.out.println(Arrays.toString(arr));\n int ans=Integer.MAX_VALUE;\n for(int i=0; i<arr.length && arr[i]!=0;i++)\n {\n int freq=arr[i];\n int del=0;\n //checking the how many character need to be deleted\n for(int j=0;j<arr.length && arr[j]!=0;j++)\n {\n if(arr[j]>freq+k){\n del+=arr[j]-(freq+k);\n }\n else if(arr[j]<freq) {\n del+=arr[j];\n }\n }\n // store the minimum deletion\n ans=Math.min(ans,del);\n \n }\n\n //if ans is Integer max value means no need of deletion then directly return 0\n return ans;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | 🔥 [CPP] | Freq Array (Max Freq) | cpp-freq-array-max-freq-by-rushi_mungse-cwgx | \n\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int max_freq = 0;\n vector<int> freq(26);\n for(auto &w : | rushi_mungse | NORMAL | 2024-03-17T04:01:12.098681+00:00 | 2024-03-17T04:01:12.098730+00:00 | 369 | false | \n\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int max_freq = 0;\n vector<int> freq(26);\n for(auto &w : word) max_freq = max(max_freq, ++freq[w - \'a\']);\n \n int ans = INT_MAX;\n for(int make = 0; make <= max_freq; make++) {\n int res = 0;\n for(auto &cnt : freq) {\n if(cnt < make) res += cnt;\n else if(cnt > make + k) res += cnt - make - k;\n }\n ans = min(ans, res);\n }\n \n return ans;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
minimum-deletions-to-make-string-k-special | Very easy DP Code || Intuitive || Explained | very-easy-dp-code-intuitive-explained-by-bvjb | Complexity\n- Time complexity: O(n + 2626) \n\n- Space complexity: O(2626) \n\n# Code\n\nclass Solution {\n int solve(int i, int j, int k, vector<int>& arr, | coder_rastogi_21 | NORMAL | 2024-03-20T15:03:39.051381+00:00 | 2024-03-20T15:03:39.051414+00:00 | 18 | false | # Complexity\n- Time complexity: $$O(n + 26*26)$$ \n\n- Space complexity: $$O(26*26)$$ \n\n# Code\n```\nclass Solution {\n int solve(int i, int j, int k, vector<int>& arr, vector<vector<int>>& dp)\n {\n if(i == j || arr[j] - arr[i] <= k) //base case\n return 0;\n \n if(dp[i][j] != -1) { //memoization step\n return dp[i][j];\n }\n \n int front = arr[i] + solve(i+1,j,k,arr,dp); //remove all from the start\n int back = (arr[j]-arr[i]-k) + solve(i,j-1,k,arr,dp); //or remove required from the end\n return dp[i][j] = min(front,back); //take minimum of both the cases\n }\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<int,int> m;\n //count frequency of each character\n for(auto it : word) {\n m[it]++;\n }\n \n vector<int> arr;\n for(auto [key,val] : m) {\n arr.push_back(val);\n }\n sort(arr.begin(),arr.end()); //sort the frequency\n int n = arr.size();\n vector<vector<int>> dp(n,vector<int>(n,-1)); //make dp array\n return solve(0,arr.size()-1,k,arr,dp);\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | Easy HashMap Java Solution | easy-hashmap-java-solution-by-deep_ptl-5xqo | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n1) Initialize a HashMap freqMap to store the frequency of each characte | deep_ptl | NORMAL | 2024-03-17T22:14:47.101314+00:00 | 2024-03-17T22:14:47.101344+00:00 | 43 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n1) Initialize a HashMap freqMap to store the frequency of each character in the word.\n2) Iterate through each character in the input word and update the frequency count in the freqMap.\n3) For each character c in the word:\nIf c is not already in the freqMap, add it with a frequency of 1.\nIf c is already in the freqMap, increment its frequency by 1.\n4) Initialize a variable min to store the minimum number of deletions needed.\n5) Iterate through the values of the freqMap, representing the frequencies of characters in the word.\n6) For each frequency freq:\n- Initialize a variable curr to calculate the current number of deletions for the current frequency.\n- Iterate through the values of the freqMap again to calculate the total number of deletions needed for the current frequency.\n- For each frequency j:\n- If j is less than freq, add j to curr. Otherwise, add the maximum of 0 and the difference between j, k, and freq to curr.\n7) Update the minimum number of deletions needed (min) by taking the minimum of the current number of deletions (curr) and the current minimum (min).\n8) Finally, return the minimum number of deletions needed.\n\n**Dry Run:\nInput: word = "aabcaba", k = 0\nOutput: 3\n**\n1) Initialize an empty HashMap freqMap to store the frequency of each character.\n2) Iterate through each character in the word "aabcaba":\n3) After this loop, freqMap will contain the frequencies: {\'a\':4,\'b\':2,\'c\':1}.\n4) Initialize min to Integer.MAX_VALUE\n5) Iterate over the values of freqMap\n For the first iteration, freq is 4.\n Initialize curr=0.\n Inner loop: For each frequency j in countMap.values():\n For \'a\' (freq = 4), j is 4, then curr += Math.max(0, 4 - 0 - 4) = 0+0 = 0\n For \'b\' (freq = 4), j is 2, j<freq then curr += j = 2+0 = 2\n For \'c\' (freq = 4), j is 1, j<freq then curr += j = 1+2 = 3\n Min= Math.min(Integer.MAX_VALUE,curr) = 3\n\n For \'a\' (freq = 2) , j is 4, then curr + = Math.max(0, 4-0-2)=2+0=2\n For \'b\' (freq = 2) , j is 2, then curr + = Math.max(0, 2-0-2)=0+2=2\n For \'c\' (freq = 2), j is 1, j<freq then curr += 1+2 =3\n Min= Math.min(Integer.MAX_VALUE,curr)= Math.min(3,3)= 3\n return 3\n\n# Complexity\n- Time complexity: O(n), first for loop iterates through each character in the input word and constructs the frequency map which takes O(n) time and second for loop iterates through the values of the frequency map which takes O(n) time. Total: O(n) time\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n), In the worst case, if all characters in the input word are unique, the space complexity is O(n), where n is the length of the input word\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumDeletions(String word, int k) {\n Map<Character, Integer> freqMap = new HashMap<>();\n for (char c : word.toCharArray()) {\n freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);\n }\n int min = Integer.MAX_VALUE;\n for (int freq : freqMap.values()) {\n int curr = 0;\n for (int j : freqMap.values()) {\n curr += j < freq ? j : Math.max(0, j - k - freq);\n System.out.println(curr);\n }\n min = Math.min(min, curr);\n System.out.println("Minimum: "+min);\n }\n return min;\n }\n}\n\n// 1) Initialize an empty HashMap freqMap to store the frequency of each character.\n// 2) Iterate through each character in the word "aabcaba":\n// 3) After this loop, freqMap will contain the frequencies: {\'a\':4,\'b\':2,\'c\':1}.\n// 4) Initialize min to Integer.MAX_VALUE\n// 5) Iterate over the values of freqMap\n// For the first iteration, freq is 4.\n// Initialize curr=0.\n// Inner loop: For each frequency j in countMap.values():\n// For \'a\' (freq = 4), j is 4, then curr += Math.max(0, 4 - 0 - 4) = 0+0 = 0\n// For \'b\' (freq = 4), j is 2, j<freq then curr += j = 2+0 = 2\n// For \'c\' (freq = 4), j is 1, j<freq then curr += j = 1+2 = 3\n// Min= Math.min(Integer.MAX_VALUE,curr) = 3\n\n// For \'a\' (freq = 2) , j is 4, then curr + = Math.max(0, 4-0-2)=2+0=2\n// For \'b\' (freq = 2) , j is 2, then curr + = Math.max(0, 2-0-2)=0+2=2\n// For \'c\' (freq = 2), j is 1, j<freq then curr += 1+2 =3\n// Min= Math.min(Integer.MAX_VALUE,curr)= Math.min(3,3)= 3\n// return 3\n``` | 2 | 0 | ['Array', 'Hash Table', 'Java'] | 0 |
minimum-deletions-to-make-string-k-special | DP | Alternative Approach | C++ | dp-alternative-approach-c-by-sparker_724-qji2 | It can be solved with simple brute force iteration. Here is an alternative approach whic uses basic dynamic programming\n# Intuition\nFor any two numbers of the | Sparker_7242 | NORMAL | 2024-03-17T08:08:31.923455+00:00 | 2024-03-17T08:08:31.923474+00:00 | 29 | false | It can be solved with simple brute force iteration. Here is an alternative approach whic uses basic dynamic programming\n# Intuition\nFor any two numbers of the frequency array, there are two possibilities - either remove the smaller one or decrease the larger one.\n\n\n# Approach\nWrite a recursive code for the two by intialising two pointers - one at start and one at end of the sorted frequency array\n\nNOTE - It will be accepted without DP as well.\n\n# Complexity\n- Time complexity:\n- O(n) with dp\n- O(max(n,2^26)) without dp\n\n- Space complexity:\nO(26*26) = O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int fn(vector<int> &v, int k, int i,int j,vector<vector<int>> &dp){\n if (dp[i][j] != -1) return dp[i][j];\n int c1 = 0, c2 = 0; int z = v[j]-v[i];\n if (z > k){\n c1 += v[i]+fn(v,k,i+1,j,dp); // removing the smaller\n c2 += (z-k)+fn(v,k,i,j-1,dp); // decreasing the larger\n } else {\n return 0;\n }\n return dp[i][j] = min(c1,c2);\n }\n int minimumDeletions(string word, int k) {\n unordered_map<char,int> m;\n for (auto x: word)m[x]++;\n vector<int> v;\n for (auto x: m)v.push_back(x.second);\n if (v.size() <= 1) return 0; // if only one kind of character is present in the string return zero\n sort(v.begin(),v.end());\n int i = 0, j = v.size()-1;\n vector<vector<int>> dp(26,vector<int>(26,-1));\n int ans = fn(v,k,i,j,dp);\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Video Explanation (Along with a HARDER VERSION) | video-explanation-along-with-a-harder-ve-qwzx | Explanation \n\nClick here for the video\n\n# Code\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int> frq(26);\n | codingmohan | NORMAL | 2024-03-17T05:47:04.168850+00:00 | 2024-03-17T05:47:04.168883+00:00 | 93 | false | # Explanation \n\n[Click here for the video](https://youtu.be/NAWNz8caFK8)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int> frq(26);\n for (auto c : word) frq[c-\'a\'] ++; \n \n int ans = 1e5;\n \n for (int l = 1; l <= 100000; l ++) {\n int r = min (l+k, 100000);\n int cost = 0;\n\n for (int ch = 0; ch < 26; ch ++) {\n if (frq[ch] < l) cost += frq[ch];\n if (frq[ch] > r) cost += (frq[ch] - r);\n }\n ans = min (ans, cost);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Intuitive recursion-based, whether to delete the least frequency one or keep it. | intuitive-recursion-based-whether-to-del-8leb | Intuition\nAfter sorting by the frequencies in descrending order, recursively consider keeping the letter with the least frequency or delete it.\n\n# Approach\n | practice_harder | NORMAL | 2024-03-17T04:17:29.684662+00:00 | 2024-03-17T06:43:06.507679+00:00 | 300 | false | # Intuition\nAfter sorting by the frequencies in descrending order, recursively consider keeping the letter with the least frequency or delete it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Count the frequencies for 26 letters\n2. Sort the frequencies in descrending order\n3. Two ways to find the final answer:\n - keep the least frequency and figure out the number of letters to be deleted.\n - delete the letter with the least frequency, and do the recursion for step 3.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$, needs to traverse the word string to get frequencies.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$, again, word size does not affect the space.\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int res = 0;\n vector<int> cnt(26, 0);\n int n = word.size();\n for (int i = 0; i < n; i++) {\n cnt[word[i]-\'a\']++;\n }\n vector<int> freq;\n for (auto x : cnt) {\n if (x > 0) {\n freq.push_back(x);\n }\n }\n sort(freq.rbegin(), freq.rend());\n // for (auto x : freq) {\n // cout << x << " ";\n // }\n func(freq, freq.size(), k, res);\n return res;\n }\n \n int func(vector<int> freq, int n, int k, int& res) {\n if (n == 0) return 0;\n if (n == 1) return 0;\n int last = freq[n-1];\n int next = func(freq, n-1, k, res)+last;\n \n for (int i = 0; i < n; i++) {\n freq[i] -= last;\n }\n int tmp = 0;\n for (int i = 0; i < n; i++) {\n tmp += max(0, freq[i]-k); \n }\n res = min(tmp, next);\n return res;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Only Using Map Explained ✅✔️ | only-using-map-explained-by-nandunk-mgnw | 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 | nandunk | NORMAL | 2024-03-17T04:08:38.364062+00:00 | 2024-03-17T04:08:38.364113+00:00 | 477 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<char,int>mp;\n for(auto it:word) mp[it]++;\n int ans=INT_MAX;\n for(auto it:mp){\n int res=0;\n int limit=it.second;\n for(auto it:mp){\n if(it.second>limit+k){\n res+=it.second-(limit+k);\n }\n else if(it.second<limit)res+=it.second; // see again\n }\n if(ans==0) break;\n ans=min(ans,res);\n }\n if(ans==INT_MAX) return 0;\n return ans;\n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | [Java Solution] Dynamic Programming With Clear Explanation | java-solution-dynamic-programming-with-c-a0lb | Intuition\nThe challenge involves balancing the frequencies of characters in a string to make it "k-special," where the frequency difference between any two cha | trtdytr | NORMAL | 2024-03-17T04:07:40.509011+00:00 | 2024-03-17T04:37:48.725879+00:00 | 111 | false | # Intuition\nThe challenge involves balancing the frequencies of characters in a string to make it "k-special," where the frequency difference between any two characters does not exceed `k`. The initial step is to understand the frequency distribution of characters, guiding the deletions needed to achieve this balance.\n\n# Approach\nThe solution starts by calculating the frequency of each character and then sorting these frequencies. Using dynamic programming and a 2D memoization array, the algorithm finds the minimum number of deletions required. \nIt compares two main actions for each step: \n- deleting from the high-frequency end (right) \n- deleting from the low-frequency end (left)\n\nrecursively determining the minimum deletions needed for each subarray.\n\n# Complexity\n- Time complexity: $$O(n)$$\nThe complexity is due to traversing the entire `word`($$O(n)$$) and sorting the frequency array ($$O(26 \\log 26)$$) and the dynamic programming solution ($$O(26^2)$$ for all subarray combinations).\n\n- Space complexity: $$O(26^2) \\approx O(1)$$\nThe space complexity is determined by the size of the 2D memoization array and the stack of recursive calls, which is a constant $$O(26^2)$$, independent of the input size.\n\n\n# Code\n```\nclass Solution {\n final int MAX = 100_001;\n public int minimumDeletions(String word, int k) {\n int[] freq = new int[26];\n for (char c : word.toCharArray()) {\n freq[c - \'a\']++;\n }\n \n Arrays.sort(freq);\n int l = 0, r = 25;\n int[][] memo = new int[26][26];\n for (int i = 0; i < 26; i++) {\n Arrays.fill(memo[i], MAX);\n }\n int deletion = getMinDeletion(freq, 0, 25, k, memo);\n \n return deletion;\n }\n \n private int getMinDeletion(int[] freq, int l, int r, int k, int[][] memo) {\n if (memo[l][r] != MAX) return memo[l][r];\n if (freq[r] - freq[l] <= k) return 0;\n \n // first plan is deleting from the right:\n int plan1 = freq[r] - (freq[l] + k) + getMinDeletion(freq, l, r - 1, k, memo);\n // second plan is deleting from the left:\n int plan2 = freq[l] + getMinDeletion(freq, l + 1, r, k, memo);\n \n memo[l][r] = Math.min(plan1, plan2);\n \n return memo[l][r];\n }\n}\n``` | 2 | 0 | ['Dynamic Programming', 'Java'] | 1 |
minimum-deletions-to-make-string-k-special | O(n) Solution | Rust | on-solution-rust-by-prog_jacob-kuch | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co | Prog_Jacob | NORMAL | 2024-03-17T04:05:04.440808+00:00 | 2024-03-17T16:30:42.275672+00:00 | 15 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimpl Solution {\n pub fn minimum_deletions(word: String, k: i32) -> i32 {\n let mut map = [0; 26];\n let mut ans = i32::MAX;\n\n for ch in word.chars() {\n map[ch as usize - 97] += 1;\n }\n \n \n for &x in map.iter() {\n let high = x + k;\n \n ans = ans.min(\n map.iter().map(|&y| {\n if y > high { y - high }\n else if y < x { y }\n else { 0 }\n }).sum()\n );\n }\n \n ans\n }\n}\n``` | 2 | 0 | ['Rust'] | 0 |
minimum-deletions-to-make-string-k-special | check all ranges from 0 to k to (maxfreq - k) to (maxfreq) | check-all-ranges-from-0-to-k-to-maxfreq-qizje | 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 | batman654 | NORMAL | 2024-03-17T04:04:04.377691+00:00 | 2024-03-17T04:35:35.081055+00:00 | 130 | 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#define ll long long\n\nll find(int low, int high, vector<int> &fr)\n{\n ll res = 0;\n \n for(int i=0; i<fr.size(); ++i)\n {\n int curr = fr[i];\n \n if(curr < low)\n res+=curr;\n else if(curr > high)\n res+=curr-high; \n }\n\n return res;\n}\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n \n unordered_map<char, int> m;\n \n for(int i=0; i<word.length(); ++i)\n m[word[i]]+=1;\n \n vector<int> fr;\n \n for(auto i=m.begin(); i!=m.end(); ++i)\n fr.push_back(i->second);\n\n \n sort(fr.begin(), fr.end());\n int mx = fr.back();\n\n int low = 0;\n int high = k;\n \n ll res = 1e9;\n bool stat = true;\n \n while(high <= mx)\n {\n ll now = find(low, high, fr);\n res = min(now, res);\n \n ++low;++high;\n stat = false;\n }\n \n if(stat)\n return 0;\n\n return res; \n }\n};\n\n\n``` | 2 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Hasp Map Solution | hasp-map-solution-by-tlecodes-xbxg | 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 | tlecodes | NORMAL | 2024-10-08T11:46:18.983050+00:00 | 2024-10-08T11:46:18.983067+00:00 | 8 | 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```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int ans = INT_MAX, cnt;\n vector<int> freq(26, 0);\n for (char ch : word) {\n freq[ch - \'a\']++;\n }\n for (auto num : freq) {\n if (num) {\n cnt = 0;\n for (int index = 0; index < 26; index++) {\n if (freq[index] < num) {\n cnt += freq[index];\n } else if (freq[index] > (num + k)) {\n cnt += freq[index] - (num + k);\n }\n }\n ans = min(ans, cnt);\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | [Python] count freq | python-count-freq-by-pbelskiy-9h5b | \nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n\n @cache\n def dfs(left, right):\n d = a[right] - a[left | pbelskiy | NORMAL | 2024-03-23T14:43:14.540076+00:00 | 2024-03-23T14:43:14.540093+00:00 | 6 | false | ```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n\n @cache\n def dfs(left, right):\n d = a[right] - a[left]\n if d <= k:\n return 0\n\n return min(\n dfs(left + 1, right) + a[left], # remove\n dfs(left, right - 1) + d - k, # reduce\n )\n\n a = sorted(Counter(word).values())\n return dfs(0, len(a) - 1)\n``` | 1 | 0 | ['Python'] | 0 |
minimum-deletions-to-make-string-k-special | Leelavardhan's Java Solution 5ms | leelavardhans-java-solution-5ms-by-klu_2-79h1 | Intuition\n Describe your first thoughts on how to solve this problem. \n Calculate the frequency of each Character and store them into a array and do sort and | klu_2200031318 | NORMAL | 2024-03-23T11:02:29.342672+00:00 | 2024-03-23T11:02:29.342702+00:00 | 51 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Calculate the frequency of each Character and store them into a array and do sort and follow the approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe question is about to delete minimum characters so that the difference between frequency of i th and j th character of the word must be less or equal to k size.\nNow the approach is \n\nStep:1\n==> **First Take two loops here --> the first loop which iterates each element in the array.**\n\nStep:2\n==> **Now in the second loop-->** add **K** to one of the element \n**freq[i]** and checks the minimum value with the remaining elements \n**freq[j]** added to one declared variable so called **sum**\n\nStep:3\n==> Now take a **Max variable=Datatype large value range** , checks Minimum value with **Word length minus sum** \nDo the above step 2 and 3 iterately you will get the answer \n\nThank you.\n\n**Leelavardhan** \n\n\n\n# Complexity\n- Time complexity:O(N+26*26)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:O(30)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int freq[]=new int[26];\n for(int i=0;i<word.length();i++){\n freq[word.charAt(i)-\'a\']++;\n }\n Arrays.sort(freq);\n int res=Integer.MAX_VALUE;\n for(int i=0;i<26;i++){\n int sum=0;\n if(freq[i]!=0){\n \n for(int j=i;j<26;j++){\n if(freq[j]!=0){\n sum+=Math.min(freq[i]+k,freq[j]);\n }\n res=Math.min(res,word.length()-sum);\n }\n }\n }\n return res;\n\n \n \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | [C++ / Go] Sliding Window - O(n) time / O(26) space solution | c-go-sliding-window-on-time-o26-space-so-c03i | Approach\n- Count the number of occurrences of each character and then sort them in ascending order.\n- Iterate l through the counting array cnt:\n - Maintai | mikazuki4712 | NORMAL | 2024-03-19T17:05:12.931445+00:00 | 2024-03-19T17:05:12.931482+00:00 | 39 | false | # Approach\n- Count the number of occurrences of each character and then sort them in ascending order.\n- Iterate `l` through the counting array `cnt`:\n - Maintain a sliding window with 2 ends `l` and `r`, where `cnt[r] - cnt[l] <= k` and `r` is maximum.\n - Here we perform deletions to ensure that all occurrences of each character are either reduced to `0` or remain within the range from `cnt[l]` to `cnt[l] + k`.\n - The part from `0` to `l - 1`, all characters will be deleted all to 0.\n - The part from `r + 1` to `25`, all characters will be deleted down to `cnt[l] + k` occurences.\n - \n\n# Code\n```C++ []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int> cnt(26, 0);\n for (char c : word)\n cnt[c - \'a\']++;\n\n sort(cnt.begin(), cnt.end());\n \n int res = INT_MAX;\n\n int leftSum = 0;\n int rightSum = 0;\n\n int r = 25;\n while (cnt[r] > cnt[0] + k) {\n rightSum += cnt[25] - cnt[r];\n r--;\n }\n\n for (int l = 0; l < 26; l++) {\n if (l > 0)\n leftSum += cnt[l - 1];\n\n int m = cnt[l] + k;\n while (r < 25 && cnt[r + 1] <= m) {\n r++; \n rightSum -= cnt[25] - cnt[r];\n }\n \n res = min(res, leftSum + (25 - r) * (cnt[25] - m) - rightSum);\n }\n \n return res;\n }\n};\n```\n```Go []\nfunc minimumDeletions(word string, k int) int {\n cnt := make([]int, 26)\n\tfor _, c := range word {\n\t\tcnt[c - \'a\']++\n\t}\n\n\tsort.Ints(cnt)\n\n\tres := len(word)\n\n\tleftSum := 0\n\trightSum := 0\n\n\tr := 25\n\tfor ; cnt[r] > cnt[0] + k; r-- {\n\t\trightSum += cnt[25] - cnt[r]\n\t}\n\n\tfor l := 0; l < 26; l++ {\n\t\tif l > 0 {\n\t\t\tleftSum += cnt[l - 1]\n\t\t}\n\n\t\tm := cnt[l] + k\n\t\tfor r < 25 && cnt[r + 1] <= m {\n\t\t\tr++\n\t\t\trightSum -= cnt[25] - cnt[r]\n\t\t}\n\n tmp := leftSum + (25 - r) * (cnt[25] - m) - rightSum\n if (res > tmp) {\n res = tmp\n }\n\t}\n\n\treturn res\n}\n```\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(26)$ | 1 | 0 | ['Sliding Window', 'C++', 'Go'] | 0 |
minimum-deletions-to-make-string-k-special | 7 Line Dynamic Programming Solution using Counter, O(n) runtime. | 7-line-dynamic-programming-solution-usin-psnk | I and J are restricted by O(26) for each since there is 26 char in the alphabet. So our runtime is O(n) from len(word) = n and spacetime is O(26 * 26) ~ O(1). \ | robert961 | NORMAL | 2024-03-18T19:38:37.544522+00:00 | 2024-03-18T19:38:37.544552+00:00 | 46 | false | I and J are restricted by O(26) for each since there is 26 char in the alphabet. So our runtime is O(n) from len(word) = n and spacetime is O(26 * 26) ~ O(1). \n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n cnt = Counter(word)\n c = deque(sorted(list(cnt.values())))\n \n @cache\n def dfs(i, j):\n if c[j] - c[i] <=k: return 0\n return min(c[i] + dfs(i+1,j), max(0, c[j] - c[i] - k) + dfs(i,j-1))\n \n return dfs(0, len(c) -1)\n \n \n \n \n\n\n \n \n``` | 1 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
minimum-deletions-to-make-string-k-special | Recursive C++ Solution | recursive-c-solution-by-anupsingh556-q3hb | Intuition\n- sort frequency array in descending order\n- we can either reduce minimum freq to 0 or make max freq to min(freq) + k\n- use recursion to find minim | anupsingh556 | NORMAL | 2024-03-18T09:07:36.673589+00:00 | 2024-03-18T09:07:36.673615+00:00 | 8 | false | # Intuition\n- sort frequency array in descending order\n- we can either reduce minimum freq to 0 or make max freq to min(freq) + k\n- use recursion to find minimum from both operations\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int> freq(26, 0);\n for(int i=0;i<word.size();i++)freq[word[i]-\'a\']++;\n sort(freq.begin(), freq.end());\n int end = 25,beg=0;\n for(int i=0;i<26;i++)if(freq[i]!=0){\n beg=i;\n break;\n }\n return minimumDel(freq, k, beg, end);\n }\n \n int minimumDel(vector<int>& a, int k, int start, int end) {\n if(start==end || a[end]-a[start]<=k)return 0;\n return min(a[start] + minimumDel(a, k, start+1, end), a[end]-a[start]-k+minimumDel(a, k, start, end-1));\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Easy C++ solution | Beats 100% solutions | easy-c-solution-beats-100-solutions-by-a-j2a2 | Intuition\nCalculate the frequencies of all characters in the string. Since we can only delete a character (that is reduce the frequency of character), we can l | ankitjangir001 | NORMAL | 2024-03-18T04:21:17.919380+00:00 | 2024-03-18T04:21:17.919425+00:00 | 48 | false | # Intuition\nCalculate the frequencies of all characters in the string. Since we can only delete a character (that is reduce the frequency of character), we can loop for all frequencies of chars keeping an `target` value and adjusting all frequencies suitable to that `target`. If for a `target`, the freq of char is less than `target`, we have to make its frequency `0` (as we can not increase freq), otherwise if freq of char is greater than `target`, we need to make sure it should not greater than `target + k`.\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int> freq(26, 0); \n \n for(char c : word){\n freq[c - \'a\']++;\n }\n \n int res = INT_MAX;\n \n for(int i=0; i < 26; i++){\n int target = freq[i];\n if(target == 0) continue;\n int currCost = 0;\n\n for(int a : freq){\n // maintain \'a\' within the range [target, target + k]\n if(a < target){\n currCost += a;\n }\n else if(a > target + k){\n currCost += a - target - k;\n }\n }\n\n res = min(res, currCost);\n }\n\n return res;\n \n }\n};\n```\n\nimage.png\n | 1 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Simple python3 solution | 85 ms - faster than 100.00% solutions | simple-python3-solution-85-ms-faster-tha-xyzq | Complexity\n- Time complexity: O(n + m) = O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(m) = O(1)\n Add your space complexity here, | tigprog | NORMAL | 2024-03-17T23:17:25.778171+00:00 | 2024-03-17T23:17:25.778207+00:00 | 161 | false | # Complexity\n- Time complexity: $$O(n + m) = O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m) = O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere `m = 26` - number of lowercase English letters\n\n# Code\n``` python3 []\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n count = sorted(Counter(word).values())\n \n prefix = 0\n suffix = sum(count)\n \n m = len(count)\n j = 0\n\n result = suffix\n for i, a in enumerate(count):\n while j < m and count[j] - a <= k:\n suffix -= count[j]\n j += 1\n current = prefix + suffix - (m - j) * (a + k)\n result = min(result, current)\n prefix += a\n return result\n``` | 1 | 0 | ['Two Pointers', 'Sliding Window', 'Sorting', 'Counting', 'Python3'] | 0 |
minimum-deletions-to-make-string-k-special | ⚡Greedy || 🌟Sorting || 🔥HashMap | greedy-sorting-hashmap-by-adish_21-3ka5 | \n\n# Complexity\n\n- Time complexity:\nO(26 * 26)\n\n- Space complexity:\nO(26)\n\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n\nclass Solution {\npubl | aDish_21 | NORMAL | 2024-03-17T07:36:23.041447+00:00 | 2024-03-17T08:44:49.870294+00:00 | 111 | false | \n\n# Complexity\n```\n- Time complexity:\nO(26 * 26)\n\n- Space complexity:\nO(26)\n```\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int n = word.size(), mini = INT_MAX;\n unordered_map<char, int> mp;\n for(auto it : word)\n mp[it]++;\n vector<int> vec;\n for(auto it : mp)\n vec.push_back(it.second);\n sort(vec.begin(), vec.end());\n int m = vec.size(), prefix = 0;\n for(int i = 0 ; i < m ; i++){\n int j = m - 1, tmp = 0;\n while(vec[j] - vec[i] > k)\n tmp += (vec[j--] - vec[i] - k);\n mini = min(mini, prefix + tmp);\n if(!tmp)\n break;\n prefix += vec[i];\n }\n return mini;\n }\n};\n``` | 1 | 0 | ['Greedy', 'Ordered Map', 'Sorting', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | Minimum Deletions to Make String K-Special | minimum-deletions-to-make-string-k-speci-mus9 | Intuition\nvery simple\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 | darthVader26 | NORMAL | 2024-03-17T05:43:33.619235+00:00 | 2024-03-17T05:43:33.619282+00:00 | 159 | false | # Intuition\nvery simple\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 solve(int []ch,int i,int j,int k,int dp[][]){\n if(i==j || ch[j]-ch[i]<=k) return 0;\n if(dp[i][j]!=-1) return dp[i][j];\n return dp[i][j]=Math.min(ch[i]+solve(ch,i+1,j,k,dp), ch[j]-ch[i]-k+solve(ch,i,j-1,k,dp));\n }\n public int minimumDeletions(String w, int k) {\n \n int ch[] = new int[26];\n for (char c : w.toCharArray()) {\n ch[c - \'a\']++;\n }\n \n Arrays.sort(ch);\n int dp[][]=new int[26][26];\n for(int row[]: dp) Arrays.fill(row,-1);\n return solve(ch,0,25,k,dp);\n }\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Memoization', 'Java'] | 1 |
minimum-deletions-to-make-string-k-special | DP Memoization | dp-memoization-by-kushal1605-4fvo | 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 | Kushal1605 | NORMAL | 2024-03-17T05:18:28.200224+00:00 | 2024-03-17T05:18:28.200249+00:00 | 59 | 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 Integer [][] dp;\n public int helper(List<Integer> arr, int start, int end, int k) {\n if(start >= end) {\n return 0;\n }\n \n int diff = arr.get(end) - arr.get(start);\n if(diff <= k) {\n return 0;\n }\n \n if(dp[start][end] != null) {\n return dp[start][end];\n }\n\n int remove = arr.get(start) + helper(arr, start + 1, end, k);\n int reduce = diff - k + helper(arr, start, end - 1, k);\n \n return dp[start][end] = Math.min(remove, reduce);\n }\n\n public int minimumDeletions(String word, int k) {\n Map<Character, Integer> freq = new HashMap<>();\n \n for(char c : word.toCharArray()) {\n freq.put(c, freq.getOrDefault(c, 0) + 1);\n }\n \n List<Integer> arr = new ArrayList<>(freq.values());\n arr.sort(null);\n \n this.dp = new Integer [26][26];\n return helper(arr, 0, arr.size() - 1, k);\n }\n}\n\n``` | 1 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Minimum Deletions to make String K-Special: Efficient HashMap Algo | minimum-deletions-to-make-string-k-speci-ywsa | Intuition\nThe intuition behind this code is to find the minimum number of deletions required to make the frequency of each character in the string word at most | madhusudanrathi99 | NORMAL | 2024-03-17T05:05:28.938889+00:00 | 2024-03-17T05:05:28.938907+00:00 | 58 | false | # Intuition\nThe intuition behind this code is to find the minimum number of deletions required to make the frequency of each character in the string `word` at most `k`.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. **Initialize Variables**: \nThe code initializes a dictionary `map` to store the frequency of each character in `word`, a list `vals` to store the frequencies, and integers `sumOfLess`, `ans`, and `n` to store the sum of frequencies less than the current frequency, the minimum number of deletions, and the number of distinct characters in `word` respectively.\n2. **Count Frequencies**: \nThe code then iterates over the characters in `word` and increments their frequency in `map`.\n3. **Store Frequencies**: \nThe code stores the frequencies in `vals` and sorts `vals`.\n4. **Calculate Minimum Deletions**: \nThe code iterates over `vals`. For each frequency `vals[i]`, it calculates the sum of frequencies less than `vals[i]` and the sum of differences between frequencies greater than `vals[i]` and `k`. It updates `ans` with the minimum of `ans` and the calculated sum.\n5. **Return Minimum Deletions**: \nThe code returns `ans`, which represents the minimum number of deletions required to make the frequency of each character at most `k`.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N \\log 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```\npublic class Solution {\n public int MinimumDeletions(string word, int k) {\n Dictionary<char, int> map = new Dictionary<char, int>();\n foreach(char ch in word) {\n if(!map.ContainsKey(ch))\n map[ch] = 0;\n map[ch]++;\n }\n \n List<int> vals = new List<int>();\n foreach(var item in map)\n vals.Add(item.Value);\n vals.Sort();\n \n int sumOfLess = 0;\n int ans = int.MaxValue;\n int n = vals.Count;\n for(int i = 0; i < n; i++) {\n if(i > 0)\n sumOfLess += vals[i - 1];\n int sum = sumOfLess;\n for(int j = i + 1; j < n; j++) {\n if(vals[j] - vals[i] > k)\n sum += vals[j] - vals[i] - k;\n }\n ans = Math.Min(ans, sum);\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Hash Table', 'String', 'Sorting', 'C#'] | 0 |
minimum-deletions-to-make-string-k-special | Explained-Solution with Intuition || AC ✅ | explained-solution-with-intuition-ac-by-g1sh1 | Intuition\n * We want to make freq[i] - freq[j] <=k for all i and j. \n * find frequency of all characters and sort them. \n * At max we have 26 characters s | satyam_9911 | NORMAL | 2024-03-17T04:28:10.007787+00:00 | 2024-03-17T04:33:29.564010+00:00 | 98 | false | # Intuition\n * We want to make ```freq[i] - freq[j] <=k ``` for all `i` and `j`. \n * find frequency of all characters and sort them. \n * At max we have 26 characters so , size of the `freq` can be of `26`.\n * Now , as we can only decrease the freq of characaters , so first we choose `freq[0]` as `minimum`.\n \n * ``` ans+=max(0 , freq[i] - freq[0] - k) ``` \n \n\n* so , minimize the ans by considering `freq[i]` as minimum and deleting all previous frequencies which is `preSum`. \n\n* ```ans = min(ans , completely deleted till ith index + partially deleted from i+1 to n)```\n\n# Complexity\n- Time complexity:\n ```O(n) + O(26log26) ~ O(n)```\n\n- Space complexity:\n ```O(n)```\n\n# Code\n```\nclass Solution {\npublic: \n \n\n int minimumDeletions(string s , int k) {\n \n int n = s.length(); \n map<int,int> map; \n \n for(char ch : s){\n map[ch]++; \n } \n \n vector<int> freq; \n \n for(auto it : map){\n freq.push_back(it.second); \n } \n \n // Sort the frequencies\n sort(freq.begin() , freq.end()); \n \n // If we take minimum as freq[0] and convert all other frequencies \n // such that abs(freq[0] - freq[i]) <=k\n int ans = 0; \n for(int i = 0 ; i < freq.size() ; i++){\n ans+=max(0 , freq[i] - freq[0] - k); \n }\n \n // preSum denotes that how many frequencies we already deleted \n // completely till Ith index\n int preSum = 0; \n \n for(int i = 0 ; i < freq.size() ; i++){ \n \n int temp = preSum; \n\n // we consider freq[i] as new minimum\n\n for(int j = i ; j < freq.size() ; j++){\n temp+=max(0 , freq[j]-freq[i] - k); \n } \n \n ans = min(ans , temp); \n preSum+=freq[i]; \n }\n \n return ans; \n \n \n }\n};\n``` | 1 | 0 | ['Hash Table', 'Sorting', 'Prefix Sum', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | [With Explanation] Frequency + Sort | with-explanation-frequency-sort-by-manis-wrcj | Code Explanation\n\nFill the Frequency Array: Iterate through each character of the input word and increment the count in corresponding position.\n\nSort the Fr | manisreekar | NORMAL | 2024-03-17T04:22:45.705035+00:00 | 2024-03-17T04:56:44.159117+00:00 | 102 | false | # Code Explanation\n\n**Fill the Frequency Array:** Iterate through each character of the input word and increment the count in corresponding position.\n\n**Sort the Frequency Array:** The count array is sorted so that it simplifies the process of calculating the minimum deletions required.\n\n**Calculate Minimum Deletions:** The idea is to fix a frequency, count[i], and calculate the cost to make all subsequent frequencies either equal to or not more than count[i] + k. This is done by iterating over the sorted frequency array and for each frequency:\n\nAdd up the frequencies (prefix_sum) as you move forward. This helps in calculating the deletions required for making frequencies equal to or less than count[i] + k.\n\nFor each frequency greater than count[i] + k, calculate the difference and add it to curr. This represents the deletions needed to decrease these frequencies to count[i] + k.\n\nUpdate the answer with the minimum of its current value and curr to keep track of the minimum deletions required.\n\n**Time Complexity :** O(n + 26log26) -> O(n)\n\n**Space Complexity :** O(26) -> O(1)\n\n# Code\n```\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int count[]=new int[26];\n \n // Count the frequency of each character in the word\n for(int i=0;i<word.length();i++)\n count[word.charAt(i)-\'a\']++;\n \n // Sort the frequency array in ascending order\n Arrays.sort(count);\n \n int answer=Integer.MAX_VALUE;\n\n int prefix_sum=0;\n \n // Iterate over each character frequency\n for (int i=0; i <count.length; i++) {\n // Skip if character frequency is 0\n if(count[i]==0)\n continue;\n\n // Current deletion count starts with prefix_sum\n int curr=prefix_sum;\n \n // Check for characters with frequency higher than the limit (count[i] + k)\n for (int j=i+1; j<count.length; j++) {\n // If frequency is too high, calculate necessary deletions\n if(count[j]>count[i]+k)\n curr+=count[j]-(count[i]+k);\n }\n\n // Update answer with the minimum deletion count found\n answer=Math.min(answer,curr);\n \n // Update prefix_sum with the current character\'s frequency\n prefix_sum+=count[i];\n }\n \n // Return the minimum deletions required, or 0 if no deletions needed\n return answer==Integer.MAX_VALUE?0:answer;\n }\n}\n\n``` | 1 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Python: frequencies of characters, linear solution | python-frequencies-of-characters-linear-kugvt | Intuition\n\nIt is clear that the string does not matter and you need to calculate the frequencies of each characters and sort them.\n\nLets assume that your ar | salvadordali | NORMAL | 2024-03-17T04:14:42.223532+00:00 | 2024-03-17T04:14:42.223554+00:00 | 33 | false | # Intuition\n\nIt is clear that the string does not matter and you need to calculate the frequencies of each characters and sort them.\n\nLets assume that your array is `1, 3, 5, 5, 7, 8, 9, 11, 14` and `k = 4`.\n\nIf you start at position `2`, then you need to remove all the frequencies below this position (cost will be 1 + 3) and then decrease all the frequencies above `5 + k` to this value (cost will be `11 - 9 + 14 - 9`). You do not even need to do this efficiently as array is 32 characters, but you can do this in log linear time (for array of arbitrary size)\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n```\nclass Solution:\n\n def minimumDeletions(self, word: str, k: int) -> int:\n arr = sorted(list(Counter(word).values()))\n suffix_sum = [0] * (len(arr) + 1)\n for i in range(len(arr) - 1, -1, -1):\n suffix_sum[i] = suffix_sum[i + 1] + arr[i]\n\n curr_sum, res = 0, float(\'inf\')\n for i in range(len(arr)):\n pos = bisect_right(arr, arr[i] + k)\n num_left = len(arr) - pos\n\n tmp = suffix_sum[pos] - num_left * (arr[i] + k) + curr_sum\n res = min(res, tmp)\n curr_sum += arr[i]\n \n return res\n``` | 1 | 0 | ['Python'] | 1 |
minimum-deletions-to-make-string-k-special | Hashmap + Sort + Binary Search + Recursion JS | hashmap-sort-binary-search-recursion-js-6hw8a | \n# Code\n\n/**\n * @param {string} word\n * @param {number} k\n * @return {number}\n */\nvar minimumDeletions = function(word, k) {\n const map = new Map()\ | geeni_10 | NORMAL | 2024-03-17T04:04:27.365576+00:00 | 2024-03-17T04:04:27.365604+00:00 | 111 | false | \n# Code\n```\n/**\n * @param {string} word\n * @param {number} k\n * @return {number}\n */\nvar minimumDeletions = function(word, k) {\n const map = new Map()\n \n for (const char of word) {\n if (map.has(char)) {\n map.set(char, map.get(char) + 1)\n } else {\n map.set(char, 1)\n }\n }\n \n let vals = [...map.values()]\n vals.sort((a, b) => a - b)\n \n const traverse = (index) => {\n if (index >= vals.length) return 0\n \n let tmp = 0\n const startIndex = binarySearch(vals, vals[index] + k + 1)\n for (let i = startIndex; i < vals.length; i++) {\n if (vals[i] - vals[index] <= k) continue\n tmp += (vals[i] - vals[index] - k)\n }\n \n return Math.min(tmp, vals[index] + traverse(index + 1))\n }\n \n return traverse(0)\n};\n\n\nlet binarySearch = (arr, target) => {\n let left = 0;\n let right = arr.length;\n while (left < right) {\n let mid = Math.floor((left + right) / 2);\n if (arr[mid] >= target) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n return left;\n}\n``` | 1 | 0 | ['JavaScript'] | 2 |
minimum-deletions-to-make-string-k-special | C++ || EASY || Hashing || beginner friendly | c-easy-hashing-beginner-friendly-by-been-gd53 | \n\n# Code\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n // Count the frequencies of characters in the word\n vec | SprihaAnand | NORMAL | 2024-03-17T04:01:39.423026+00:00 | 2024-03-17T04:01:39.423059+00:00 | 73 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n // Count the frequencies of characters in the word\n vector<int> freq(26, 0);\n for (char c : word) {\n freq[c - \'a\']++;\n }\n \n // Extract the frequencies and sort them in descending order\n sort(freq.begin(), freq.end(), greater<int>());\n \n // Initialize variables for the minimum deletions and the target frequency list\n int min_deletions = INT_MAX;\n \n // Iterate over the possible target frequencies\n for (int i = 0; i < freq.size(); ++i) {\n int target = freq[i];\n int deletions = 0;\n // For each target, compute the deletions needed for all other frequencies\n for (int j = 0; j < freq.size(); ++j) {\n if (freq[j] > target + k) {\n deletions += freq[j] - (target + k);\n } else if (freq[j] < target) {\n deletions += freq[j];\n }\n }\n // Keep track of the minimum deletions found so far\n min_deletions = min(min_deletions, deletions);\n \n if (min_deletions == 0) { // Early exit if no deletions needed\n break;\n }\n }\n \n return min_deletions != INT_MAX ? min_deletions : 0;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Hash Function', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | Python3 solution || Beginner friendly | python3-solution-beginner-friendly-by-sy-o33k | \nclass Solution(object):\n def minimumDeletions(self, word, k):\n a=list(Counter(word).values())\n a.sort(reverse=True)\n ans=float("in | Syamkrishnareddypulagam | NORMAL | 2024-03-17T04:00:56.999743+00:00 | 2024-03-17T04:04:25.309300+00:00 | 221 | false | ```\nclass Solution(object):\n def minimumDeletions(self, word, k):\n a=list(Counter(word).values())\n a.sort(reverse=True)\n ans=float("inf")\n for i in range(len(a)):\n temp=0\n for j in a:\n """\n j can be in 3 cases. \n 1.either a[i]-k<=j<=a[i]+k which we actually need\n 2.j<a[i] --> in this we directly remove j elements of that respective character\n 3.j>a[i]+k --> here we remove only j-(a[i]+k) character which is minimum characters to remove to make string k-Special\n \n we are checking min_del for each string in word to make other character be in range count(string)-k<count(ele)<count(string)+k\n """\n if j>a[i]+k: #we should remove extra characters of j to make it equal to a[i]+k\n temp+=j-(a[i]+k)\n elif j<a[i]:\n temp+=j\n ans=min(temp,ans)\n if ans==0:\n break\n if ans!=float("inf"):\n return ans\n return 0\n \n``` | 1 | 1 | ['Array', 'Hash Table', 'Math', 'Sorting', 'Python3'] | 1 |
minimum-deletions-to-make-string-k-special | Interesting efficient O(n) O(1) solution | interesting-efficient-on-o1-solution-by-mttbw | IntuitionApproachComplexity
Time complexity: O(n)
Space complexity: O(1)
Code | shmirrakhimov | NORMAL | 2025-03-27T18:34:48.567035+00:00 | 2025-03-27T18:34:48.567035+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {string} word
* @param {number} k
* @return {number}
*/
var minimumDeletions = function(word, k) {
let freq = new Array(26).fill(0);
for(let i = 0; i < word.length; i++) freq[word.charCodeAt(i) - 97]++;
freq.sort((a, b) => a - b);
let start = 0;
for(let i = 0; i < 26; i++) if(freq[i] != 0) { start = i; break; }
let min = Infinity;
let prevEliminated = 0;
for(let i = start; i < freq.length; i++){
let curEqualize = 0;
for(let j = i+1; j < freq.length; j++) if(freq[i] + k < freq[j]) curEqualize += freq[j] - k - freq[i];
min = Math.min(min, curEqualize + prevEliminated);
prevEliminated += freq[i];
}
return min;
};
``` | 0 | 0 | ['Hash Table', 'Sorting', 'Counting', 'JavaScript'] | 0 |
minimum-deletions-to-make-string-k-special | 🚀 Mastering Character Deletions: The Ultimate Strategy to Minimize Changes! 🔥Easy Explanation! | mastering-character-deletions-the-ultima-lco1 | IntuitionThe goal of this problem is to minimize the number of character deletions required to make the frequency difference between the most and least occurrin | Saurabhabd_360-45 | NORMAL | 2025-02-13T14:01:53.961030+00:00 | 2025-02-13T14:01:53.961030+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The goal of this problem is to minimize the number of character deletions required to make the frequency difference between the most and least occurring characters at most k. This is done by removing characters with either the lowest or highest frequency.
# Approach
<!-- Describe your approach to solving the problem. -->
Count character frequencies: We first count the frequency of each character in the input string.
Sort the frequencies: Sorting helps in efficiently removing either the least or most frequent character.
Use recursion with memoization:
We use a recursive function func(i, j, list, k, dp) where:
i represents the index of the smallest frequency.
j represents the index of the largest frequency.
dp[i][j] stores the minimum deletions required for the range [i, j].
If the frequency difference list[j] - list[i] is already ≤ k, we return 0 (no deletions needed).
Otherwise, we have two options:
Remove the character with the smallest frequency (list[i]) and recurse on the remaining range [i+1, j].
Reduce the highest frequency list[j] to list[i] + k and recurse on [i, j-1].
We take the minimum deletions from both choices and store the result in dp[i][j].
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(26*26)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(27*27)
# Code
```java []
import java.util.*;
class Solution {
public int func(int i, int j, List<Integer> list, int k, int[][] dp) {
// Base case: If the difference between max and min frequency is within k, no deletions needed
if (list.get(j) - list.get(i) <= k) return 0;
// Return the already computed result to avoid recomputation
if (dp[i][j] != -1) return dp[i][j];
// Option 1: Remove the character with the smallest frequency
int removeMin = list.get(i) + func(i + 1, j, list, k, dp);
// Option 2: Reduce the highest frequency to (list[i] + k) and delete the excess
int removeMax = (list.get(j) - (list.get(i) + k)) + func(i, j - 1, list, k, dp);
// Store and return the minimum deletions needed
return dp[i][j] = Math.min(removeMin, removeMax);
}
public int minimumDeletions(String word, int k) {
// Step 1: Count frequency of each character
int[] arr = new int[26]; // Array to store character frequencies
for (int i = 0; i < word.length(); i++) {
arr[word.charAt(i) - 'a']++;
}
// Step 2: Store non-zero frequencies in a list
List<Integer> list = new ArrayList<>();
for (int i : arr) {
if (i > 0) {
list.add(i);
}
}
// Step 3: Sort the list to easily manipulate min and max frequencies
Collections.sort(list);
// Step 4: Initialize DP array with -1 (for memoization)
int[][] dp = new int[27][27]; // Maximum size is at most 26 unique characters
for (int[] a : dp) {
Arrays.fill(a, -1);
}
// Step 5: Call the recursive function starting from the full range
return func(0, list.size() - 1, list, k, dp);
}
}
``` | 0 | 0 | ['String', 'Dynamic Programming', 'Sorting', 'Counting', 'Java'] | 0 |
minimum-deletions-to-make-string-k-special | O(n) with sorting beating 100% | on-with-sorting-beating-100-by-lilongxue-vz92 | IntuitionCount the freq of each letter, and handle the freqs.Approach
Count the freq of each letter.
Sort the freqs.
For each index in freqs, we must try to dro | lilongxue | NORMAL | 2025-02-02T18:20:52.146052+00:00 | 2025-02-02T18:20:52.146052+00:00 | 4 | false | # Intuition
Count the freq of each letter, and handle the freqs.
# Approach
1. Count the freq of each letter.
2. Sort the freqs.
3. For each index in freqs, we must try to drop off the freqs to its left, and meanwhile, we must do some cutting from the right of the remaining array.
4. For each index, the above two operations both have a cost. We add the costs, and that's the outcome for the index.
5. The result is the minimum value of the outcomes.
6. Since there are at most 26 letters, only the counting takes O(n). All the other operations take O(1).
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(1)
# Code
```javascript []
/**
* @param {string} word
* @param {number} k
* @return {number}
*/
var minimumDeletions = function(word, k) {
const aCode = 97
const table = {}
for (let i = 0; i < 26; i++) {
const ch = String.fromCharCode(i + aCode)
table[ch] = 0
}
for (const ch of word)
table[ch]++
const freqs = [...Object.values(table)].filter(freq => freq !== 0)
freqs.sort((a, b) => a - b)
const len = freqs.length
let result = Infinity
freqs[-1] = 0
let sumSF = 0
for (let i = -1; i < len - 1; i++) {
const freq = freqs[i]
sumSF += freq
let outcome = sumSF
const leftFreq = freqs[i + 1]
for (let j = len - 1; j > i + 1; j--) {
const cutMe = freqs[j]
const reduceTo = leftFreq + k
outcome += Math.max(0, cutMe - reduceTo)
}
result = Math.min(result, outcome)
}
return result
};
``` | 0 | 0 | ['JavaScript'] | 0 |
minimum-deletions-to-make-string-k-special | Memoization DP JAVA | memoization-dp-java-by-prachikumari-wdlf | IntuitionTarget : To get minDeletion to get the character freq in range k
In order to minimise :
we can either delete the character with least freq , hence del | PrachiKumari | NORMAL | 2025-01-09T07:35:25.376605+00:00 | 2025-01-09T07:35:25.376605+00:00 | 2 | false | # Intuition
Target : To get minDeletion to get the character freq in range k
In order to minimise :
- we can either `delete the character with least freq` , hence del of character with least freq
-` Delete the character with highest freq `
# Approach
- Get all character freq in Array
- Then Sort the freqArray in ascending
- Make memo[i][j] , i, j are limit ie left , right with int the freqArray (26 letter) in order dp[l][r] contains the minimum deletions with the leftEnd and rightEnd
- 2 CHOICES :
1. LEFT DELETION : include the freq[l] int deleted cnt and recursive cal : dp[l+1], [r]
2. RIGHT DELETION : include freq[r] (exclude the valid range freq[l]+ k) & rec call dp[l][r-1]
Choose the mini of both
# Complexity
- Time complexity: O(n*26*26)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(26*26)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int minimumDeletions(String word, int k) {
int[] freq = new int[26];
for (char ch : word.toCharArray()){
freq[ch - 'a'] += 1;
}
Arrays.sort(freq);
int[][] memo= new int[26][26];
for (int[] row : memo){
Arrays.fill(row, Integer.MAX_VALUE );
}
// we have 2 options of deletions right / left from subarrays
Arrays.sort(freq);
return getMinDel(word, 0, 25, k, freq , memo);
}
private int getMinDel(String word, int l , int r, int k, int[] freq, int[][] memo){
if (memo[l][r] != Integer.MAX_VALUE) return memo[l][r];
if (freq[r] - freq[l] <= k) return 0 ;// no deletions required
// 2 option fo deletions
int rightDel = freq[r] - (freq[l]+k) + getMinDel(word, l, r-1 ,k, freq, memo);
int leftDel = freq[l] + getMinDel(word, l+1, r,k, freq , memo);
return memo[l][r] = Math.min(rightDel, leftDel);
}
}
``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Check all ranges | check-all-ranges-by-theabbie-zkxm | \nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n n = len(word)\n ctr = Counter(word)\n res = float(\'inf\')\n | theabbie | NORMAL | 2024-12-24T06:17:07.944740+00:00 | 2024-12-24T06:17:07.944774+00:00 | 1 | false | ```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n n = len(word)\n ctr = Counter(word)\n res = float(\'inf\')\n for minf in range(1, n + 1):\n maxf = minf + k\n curr = 0\n for c in ctr:\n if ctr[c] < minf:\n curr += ctr[c]\n if ctr[c] > maxf:\n curr += ctr[c] - maxf\n res = min(res, curr)\n return res\n``` | 0 | 0 | ['Python'] | 0 |
minimum-deletions-to-make-string-k-special | Constant time-space complexity Solution ( sigma = size Lang = 26 [a-z] lowercase ) leveraging maps | constant-time-space-complexity-solution-6b7he | Intuition and ApproachSee problem descriptionComplexity
Time complexity:
O(1)
Space complexity:
O(1) ( Explicit )
O(1) ( Implicit )
Code | 2018hsridhar | NORMAL | 2024-12-21T20:49:25.473765+00:00 | 2024-12-21T20:49:25.473765+00:00 | 5 | false | # Intuition and Approach
See problem description
# Complexity
- Time complexity:
$$O(1)$$
- Space complexity:
$$O(1)$$ ( Explicit )
$$O(1)$$ ( Implicit )
# Code
```python3 []
'''
URL := https://leetcode.com/problems/minimum-deletions-to-make-string-k-special/description/
3085. Minimum Deletions to Make String K-Special
Can get each let -> freq and then freq of freq, or duplicate(freqs ) too
26 letters max : reasonable bound to sigma
Complexity Analysis
Sigma = 26 ( size of langauge)
T = O(1) ( it's all sigma )
S = O(1) ( explicit ) O(1) ( implicit )
'''
class Solution:
def minimumDeletions(self, word: str, k: int) -> int:
minDel = float('inf')
freqStore = dict()
for let in word:
if(let not in freqStore):
freqStore[let] = 0
freqStore[let] += 1
records = []
for let,letFreq in freqStore.items():
record = [let,letFreq]
records.append(record)
records.sort(key = lambda x : (x[1],x[0]))
for [curLet,lowerFreq] in records:
upperFreq = lowerFreq + k
numFreqToDel = 0
for rec in records:
otherFreq = rec[1]
if(otherFreq > upperFreq):
numFreqToDel += abs(otherFreq - upperFreq)
elif(otherFreq < lowerFreq):
numFreqToDel += otherFreq
minDel = min(minDel, numFreqToDel)
return minDel
``` | 0 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | Simple Java Solution | simple-java-solution-by-sakshikishore-nu6o | Code | sakshikishore | NORMAL | 2024-12-14T19:12:01.222292+00:00 | 2024-12-14T19:12:01.222292+00:00 | 3 | false | # Code\n```java []\nclass Solution {\n int result=Integer.MAX_VALUE;\n public void Solve(int arr[],int i, int j, int score,int k)\n {\n \n if(i>=j)\n {\n result=Math.min(result,score);\n return;\n }\n if(arr[j]-arr[i]<=k)\n {\n \n result=Math.min(result,score);\n return;\n }\n\n Solve(arr,i+1,j,score+arr[i],k);\n Solve(arr,i,j-1,score+arr[j]-arr[i]-k,k);\n\n }\n public int minimumDeletions(String word, int k) {\n int ch[]=new int[26];\n for(int i=0;i<word.length();i++)\n {\n ch[word.charAt(i)-\'a\']++;\n }\n int count=0;\n for(int i=0;i<26;i++)\n {\n if(ch[i]!=0)\n {\n count++;\n }\n }\n if(count==1)\n {\n return 0;\n }\n Arrays.sort(ch);\n int arr[]=new int[count];\n int t=0;\n while(ch[t]==0)\n {\n t++;\n }\n int j=0;\n for(int i=t;i<26;i++)\n {\n arr[j]=ch[i];\n j++;\n }\n\n Solve(arr,0,count-1,0,k);\n\n return result;\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Using hashmap Step wise commented code | using-hashmap-brute-force-by-sapilol-w3gx | null | LeadingTheAbyss | NORMAL | 2024-12-11T09:15:38.096598+00:00 | 2024-12-11T09:17:00.002265+00:00 | 4 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n // Step 1: Count the frequency of each character in the word\n unordered_map<char, int> mpp;\n for (char c : word) mpp[c]++; // Iterate through the word and increment the count of each character\n\n // Step 2: Store the frequencies of the characters in a vector\n vector<int> nums;\n for (auto &[_, count] : mpp) nums.push_back(count); // Push the frequency count of each character into the vector\n\n // Step 3: Sort the frequencies in non-decreasing order\n sort(nums.begin(), nums.end()); // Sorting the frequencies helps in calculating deletions efficiently\n\n // Step 4: Initialize variables\n int n = nums.size(), mini = INT_MAX; // \'n\' is the number of unique characters, \'mini\' stores the minimum deletions\n\n // Step 5: Iterate through all possible ways of dividing the frequencies\n for (int i = 0; i < n; i++) { // Try different indices to split the frequencies\n int deleted = 0; // This will hold the number of deletions required for this particular split\n \n // Step 6: Handle characters with frequency less than or equal to the chosen frequency\n for (int j = 0; j < i; j++) // For characters with frequency less than or equal to nums[i]\n deleted += nums[j]; // We need to delete all of them\n \n // Step 7: Handle characters with frequency greater than nums[i]\n for (int j = i; j < n; j++) // For characters with frequency greater than nums[i]\n if (nums[j] - nums[i] > k) // If the difference between the frequency and nums[i] is greater than k\n deleted += (nums[j] - (nums[i] + k)); // We delete the excess characters beyond nums[i] + k\n \n // Step 8: Update the minimum deletions\n mini = min(mini, deleted); // Track the minimum deletions required\n }\n\n // Step 9: Return the result\n return mini; // Return the minimum number of deletions\n }\n};\n\n\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | C++ | c-by-tinachien-l2xk | \nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<char, int>Map;\n for(auto ch : word){\n Map | TinaChien | NORMAL | 2024-12-04T10:32:14.450551+00:00 | 2024-12-04T10:32:14.450584+00:00 | 1 | false | ```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<char, int>Map;\n for(auto ch : word){\n Map[ch]++;\n }\n vector<int>Count;\n for(auto [_, t] : Map){\n Count.push_back(t);\n }\n sort(Count.begin(), Count.end());\n int ret = INT_MAX;\n for(int i = 0; i < Count.size(); i++){\n int tmp = 0;\n int base = Count[i];\n for(int j = 0; j < Count.size(); j++){\n if(Count[j] - base > k)\n tmp += Count[j] - base - k;\n else if(Count[j] < base)\n tmp += Count[j];\n }\n ret = min(ret, tmp);\n }\n return ret;\n }\n};\n``` | 0 | 0 | [] | 0 |
minimum-deletions-to-make-string-k-special | Python 1-liner | python-1-liner-by-dsapelnikov-h6kt | Code\npython3 []\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n return (freq := Counter(list(word)).values()) and min(sum( | dsapelnikov | NORMAL | 2024-11-21T22:46:09.625143+00:00 | 2024-11-21T22:46:09.625173+00:00 | 2 | false | # Code\n```python3 []\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n return (freq := Counter(list(word)).values()) and min(sum(f if f < ref else max(f - ref - k, 0) for f in freq) for ref in freq)\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | brute force | brute-force-by-czxoxo-trd7 | 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 | czxoxo | NORMAL | 2024-11-18T22:07:24.425516+00:00 | 2024-11-18T22:07:24.425549+00:00 | 0 | 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```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n // i think the first thing we should do is abstract the counts into a hashmap or smth.\n vector<int> counts(26, 0);\n\n for (int i = 0; i < word.size(); i += 1) {\n char curr = word[i];\n counts[curr - \'a\'] += 1;\n }\n\n // how about we we two pointer this.\n // our array should be the number of unique chars in each situation right.\n sort(counts.begin(), counts.end());\n int res = INT_MAX;\n int deleted = 0;\n\n // brute force search\n for (int i = 0; i < 26; i += 1) {\n int minfreq = counts[i];\n int tmp = deleted;\n\n for (int j = 25; j > i; j -= 1) {\n if (counts[j] - counts[i] <= k) \n break;\n\n // num deletions\n tmp += counts[j] - minfreq - k;\n }\n\n res = min(res, tmp);\n deleted += minfreq;\n }\n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Freq count - Java O(26*26)|O(26) | freq-count-java-o2626o26-by-wangcai20-5k7k | Intuition\n Describe your first thoughts on how to solve this problem. \n Build freq array. \n Loop over each freq, calulate count by adding all lower freq and | wangcai20 | NORMAL | 2024-10-25T16:19:56.058780+00:00 | 2024-10-25T16:21:26.832855+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* Build freq array. \n* Loop over each freq, calulate `count` by adding all lower freq and higher freq beyond current freq + k.\n* Find the minimum `count`.\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```java []\nclass Solution {\n public int minimumDeletions(String word, int k) {\n // freq count\n int[] arr = new int[26];\n int min = Integer.MAX_VALUE;\n for (int i = 0; i < word.length(); i++)\n arr[word.charAt(i) - \'a\']++;\n for (int i = 0; i < 26; i++) {\n if (arr[i] == 0)\n continue;\n int cnt = 0;\n for (int j = 0; j < 26; j++) { // go over each freq\n if (arr[j] == 0)\n continue;\n if (arr[j] < arr[i]) // count lower freq\n cnt += arr[j];\n if (arr[j] > arr[i] + k) // highr freq count to higher freq - current freq - k\n cnt += arr[j] > k ? arr[j] - arr[i] - k : 0;\n }\n min = Math.min(min, cnt);\n }\n return min;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | [Java] ✅ 100% ✅ SLIDING WINDOW ✅ FASTEST ✅ BEST ✅ CLEAN CODE | java-100-sliding-window-fastest-best-cle-r4ia | Approach\n1. Get the frequency of the characters: charFreq[].\n2. Sort and trim (do not include 0 freq) in the charFreq. Now charFreq is like [1,1,3,4,7,8,9]\n3 | StefanelStan | NORMAL | 2024-10-25T01:43:17.857953+00:00 | 2024-10-25T01:43:17.857978+00:00 | 2 | false | # Approach\n1. Get the frequency of the characters: charFreq[].\n2. Sort and trim (do not include 0 freq) in the charFreq. Now charFreq is like [1,1,3,4,7,8,9]\n3. Looking at K (max diff), we see this is actually a window. (left, right): [1,1,3,4,7,8,9]\n - at freq of 1 (left) , you can have a max freq of 1 + k (right)\n - eg: k = 5, at index[0] (1) you window can be opened to index [3] (4). At index [4] the window is not valid: 7-1 > 5\n4. Compute the cost of eliminating all elements at the left of left.\n - For right index, everything on the right needs to be removed until freq[right]\n5. ! However, is it efficient to lower all elements to index[3] = 4 ? Our window could expant until a freq of 6 (1 + 5).\n So, in fact, everything on the right of right needs to be lowered at freq[left] + k, and not at freq[right].\n6. Use this sliding window and find the min deletions.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\n public int minimumDeletions(String word, int k) {\n int minDeletions = Integer.MAX_VALUE;\n int[] charFreq = getCharFreq(word);\n int[] prefixSum = new int[charFreq.length];\n prefixSum[0] = charFreq[0];\n for (int i = 1; i <prefixSum.length; i++) {\n prefixSum[i] = prefixSum[i-1] + charFreq[i];\n }\n for(int left = 0, right = 0; left < charFreq.length; left++) {\n while (right < charFreq.length && charFreq[left] + k > charFreq[right]) {\n right++;\n }\n minDeletions = Math.min(minDeletions, findMinDeletions(charFreq, left, Math.max(0, right - 1), prefixSum, k));\n }\n return minDeletions;\n }\n\n private int findMinDeletions(int[] charFreq, int left, int right, int[] prefixSum, int k) {\n int deletedOnLeft = left == 0 ? 0 : prefixSum[left - 1], deletedOnRight;\n if (right == charFreq.length - 1) {\n deletedOnRight = 0;\n } else {\n int rightTarget = Math.min(charFreq[left] + k, charFreq[right + 1]);\n deletedOnRight = (prefixSum[prefixSum.length - 1] - prefixSum[right]) - rightTarget * ((charFreq.length - 1) - right);\n }\n return deletedOnLeft + deletedOnRight;\n }\n\n private int[] getCharFreq(String word) {\n int[] charFreq = new int[26];\n for (int i = 0; i < word.length(); i++) {\n charFreq[word.charAt(i) - \'a\']++;\n }\n Arrays.sort(charFreq);\n int nonZeroIndex = 0;\n while(charFreq[nonZeroIndex] == 0) {\n nonZeroIndex++;\n }\n return Arrays.copyOfRange(charFreq, nonZeroIndex, charFreq.length);\n }\n``` | 0 | 0 | ['Two Pointers', 'Sliding Window', 'Java'] | 0 |
minimum-deletions-to-make-string-k-special | Beats 100% -----> Simple Approach | beats-100-simple-approach-by-vatan999-hh8v | Intuition\nThe problem involves reducing character frequencies to a manageable level by performing deletions. The goal is to minimize the number of deletions re | vatan999 | NORMAL | 2024-10-22T14:27:49.364482+00:00 | 2024-10-22T14:27:49.364518+00:00 | 0 | false | # Intuition\nThe problem involves reducing character frequencies to a manageable level by performing deletions. The goal is to minimize the number of deletions required to ensure that the difference between the frequencies of any two characters does not exceed a given threshold `k`.\n\n# Approach\n1. **Count Frequencies**: First, count the frequency of each character in the given string.\n2. **Sort Frequencies**: Store these frequencies in a vector and sort them to process from the smallest to largest.\n3. **Minimize Deletions**: For each frequency, attempt to reduce the difference between it and the larger frequencies in the vector. Count the deletions needed to ensure the difference between any two frequencies is at most `k`.\n4. **Track Minimum Deletions**: Accumulate deletions and track the minimum number of deletions needed across all attempts.\n\n# Complexity\n- **Time complexity**: Sorting the frequencies dominates the complexity, so it will be \\(O(n \\log n)\\), where \\(n\\) is the number of unique characters in the string.\n- **Space complexity**: \\(O(n)\\), where \\(n\\) is the number of unique characters in the string due to the frequency map and vector.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<char, int> mp;\n for (auto i : word) mp[i]++;\n \n vector<int> v;\n for (auto i : mp) v.push_back(i.second);\n sort(v.begin(), v.end());\n\n int ans = INT_MAX;\n int a = 0;\n\n for (int i = 0; i < v.size(); i++) {\n int b = 0;\n for (int j = i + 1; j < v.size(); j++) { \n if (v[j] - v[i] > k) b += v[j] - v[i] - k;\n }\n ans = min(ans, b + a);\n a += v[i];\n }\n ans = min(ans, a); \n return ans;\n }\n};\n```\n | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | sexy + hot code | sexy-hot-code-by-rajan_singh5639-7gdk | 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 | rajan_singh5639 | NORMAL | 2024-09-17T13:50:15.617869+00:00 | 2024-09-17T13:50:15.617903+00:00 | 0 | 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```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector <int> freq(26 , 0);\n \n for(int i =0; i<word.size(); i++)\n freq[word[i]-\'a\']++; \n \n \n\n\n\n int result = INT_MAX;\n for(int i =0; i<26; i++)\n {\n int deleted_char = 0;\n for(int j =0; j<26; j++)\n {\n if(j==i) continue;\n\n if (freq[j] < freq[i]) deleted_char += freq[j];\n \n else if(abs(freq[j] - freq[i]) > k) \n {\n deleted_char += abs(freq[j] - freq[i]-k);\n }\n\n\n }\ncout<<deleted_char<<" ";\nresult = min(result , deleted_char);\n }\n\n \n return result;\n \n \n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | HOT + SEXY CODE | hot-sexy-code-by-rajan_singh5639-eydk | 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 | rajan_singh5639 | NORMAL | 2024-09-17T11:50:06.074739+00:00 | 2024-09-17T11:50:06.074781+00:00 | 0 | 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```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector <int> freq(26 , 0);\n \n for(int i =0; i<word.size(); i++)\n freq[word[i]-\'a\']++; \n \n \n\n\n\n int result = INT_MAX;\n for(int i =0; i<26; i++)\n {\n int deleted_char = 0;\n for(int j =0; j<26; j++)\n {\n if(j==i) continue;\n\n if (freq[j] < freq[i]) deleted_char += freq[j];\n \n else if(abs(freq[j] - freq[i]) > k) \n {\n deleted_char += abs(freq[j] - freq[i]-k);\n }\n\n\n }\ncout<<deleted_char<<" ";\nresult = min(result , deleted_char);\n }\n\n \n return result;\n \n \n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | 5 ms Beats 97.91% | 5-ms-beats-9791-by-pribyte1-2vqg | Code\njava []\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int freq[]=new int[26];\n for(int i=0;i<word.length();i++ | pribyte1 | NORMAL | 2024-09-03T04:32:26.152557+00:00 | 2024-09-03T04:32:26.152598+00:00 | 1 | false | # Code\n```java []\nclass Solution {\n public int minimumDeletions(String word, int k) {\n int freq[]=new int[26];\n for(int i=0;i<word.length();i++){\n freq[word.charAt(i)-\'a\']++;\n }\n Arrays.sort(freq);\n int res=Integer.MAX_VALUE;\n for(int i=0;i<26;i++){\n int sum=0;\n if(freq[i]!=0){\n \n for(int j=i;j<26;j++){\n if(freq[j]!=0){\n sum+=Math.min(freq[i]+k,freq[j]);\n }\n res=Math.min(res,word.length()-sum);\n }\n }\n }\n return res;\n\n \n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Beats 100% time | 86% space || easy solution using frequency array | beats-100-time-86-space-easy-solution-us-x1h6 | Complexity\n- Time complexity: 0(n)\n- Beats complexity: 0(everybody)\n- Space complexity: 0(n)\n\n# Code\ncpp []\nclass Solution {\npublic:\n int minimumDel | Nazar_Zakrevski | NORMAL | 2024-08-29T09:04:33.546853+00:00 | 2024-08-29T09:04:33.546879+00:00 | 4 | false | # Complexity\n- Time complexity: 0(n)\n- Beats complexity: 0(everybody)\n- Space complexity: 0(n)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n vector<int> arr(26);\n for (int i = 0; i < word.size(); i++) {\n arr[word[i] - \'a\']++;\n }\n int ans = INT_MAX;\n for (int i = 0; i < arr.size(); i++) {\n if (arr[i] == 0) {\n continue;\n }\n int cur = 0;\n for (int j = 0; j < arr.size(); j++) {\n if (arr[j] == 0) {\n continue;\n }\n if (arr[i] > arr[j]) {\n cur += arr[j];\n }\n else {\n if (arr[j] - arr[i] > k) {\n cur += arr[j] - arr[i] - k;\n }\n }\n }\n ans = min(ans, cur);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | C++ || simple solution | c-simple-solution-by-rohityadav2002-6tty | 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 | RohitYadav2002 | NORMAL | 2024-08-20T15:09:52.597273+00:00 | 2024-08-20T15:09:52.597308+00:00 | 2 | 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```cpp []\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n unordered_map<int,int> freq;\n int n = word.size();\n for(int i = 0; i < n; i++) {\n freq[word[i] - \'a\']++;\n }\n vector<int> f;\n for(auto it : freq) {\n f.push_back(it.second);\n }\n int ans = 1e9;\n for(int i = 0; i < f.size(); i++) {\n int cnt = f[i];\n int del = 0;\n for(auto it : freq) {\n int frequency = it.second;\n if(frequency < cnt) del += frequency;\n else if(frequency > cnt + k) {\n del += frequency - (cnt+k);\n }\n }\n ans = min(del, ans);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Easy Solution C++ Greedy✅✅✅ | easy-solution-c-greedy-by-jayesh_06-aoy4 | \n\n# Code\n\nclass Solution {\npublic:\n\n int minimumDeletions(string word, int k) {\n int n = word.size();\n map<char, int> mp;\n for | Jayesh_06 | NORMAL | 2024-08-05T11:48:54.491459+00:00 | 2024-08-05T11:48:54.491496+00:00 | 0 | false | \n\n# Code\n```\nclass Solution {\npublic:\n\n int minimumDeletions(string word, int k) {\n int n = word.size();\n map<char, int> mp;\n for (int i = 0; i < n; i++) {\n mp[word[i]]++;\n }\n int i = 1, mini = n;\n int j = min(i + k, n);\n while (j <= n) {\n int op = 0;\n for (auto it : mp) {\n if (it.second < i) {\n op += (it.second);\n } else if (it.second > j) {\n op += (it.second - j);\n }\n }\n mini = min(mini, op);\n i++;\n j++;\n }\n return mini;\n }\n};\n``` | 0 | 0 | ['Hash Table', 'String', 'Greedy', 'Sorting', 'Counting', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | O(n) Soln | on-soln-by-ozzyozbourne-gq7r | Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n# Code | ozzyozbourne | NORMAL | 2024-08-01T00:08:48.506164+00:00 | 2024-08-01T00:10:15.295598+00:00 | 11 | false | # Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python []\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n map, ans = [0] * 26, float(\'inf\')\n for ch in word: map[ord(ch) - 97] += 1\n for x in map:\n current_sum = 0\n for y in map:\n if y > x + k: current_sum += (y - x - k)\n elif y < x: current_sum += y\n ans = min(ans, current_sum)\n return ans\n```\n``` rust []\nimpl Solution {\n pub fn minimum_deletions(word: String, k: i32) -> i32 {\n let (mut map, mut ans) = ([0; 26], i32::MAX);\n for ch in word.chars() { map[ch as usize - 97] += 1; }\n for &x in map.iter() {\n ans = ans.min(\n map.iter().map(|&y| {\n if y > x + k { y - x - k }\n else if y < x { y }\n else { 0 }\n }).sum()\n );\n }\n ans\n }\n}\n```\n``` java []\nfinal class Solution {\n public int minimumDeletions(final String word, final int k) {\n final int[] map = new int[26];\n var ans = Integer.MAX_VALUE;\n for (final char ch : word.toCharArray()) map[ch - 97] += 1;\n for (final int x : map) {\n var currentSum = 0;\n for (final int y : map) \n if (y > x + k) currentSum += (y - x - k);\n else if (y < x) currentSum += y;\n ans = Math.min(ans, currentSum);\n }return ans;\n }\n}\n```\n | 0 | 0 | ['Java', 'Python3', 'Rust'] | 0 |
minimum-deletions-to-make-string-k-special | Sort char frequency and check window with k | sort-char-frequency-and-check-window-wit-6ian | 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 | linda2024 | NORMAL | 2024-07-16T17:26:33.465064+00:00 | 2024-07-16T17:26:33.465112+00:00 | 3 | 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```\npublic class Solution {\n public int MinimumDeletions(string word, int k) {\n int minDel = int.MaxValue;\n Dictionary<int, int> dict = new Dictionary<int, int>();\n\n foreach(char c in word)\n {\n if(!dict.ContainsKey(c))\n dict.Add(c, 1);\n else dict[c]++;\n }\n\n List<int> valuesList = dict.Values.ToList();\n valuesList.Sort();\n\n int sumLeft = 0, len = valuesList.Count(); \n\n for(int i = 0; i < len; i++)\n {\n sumLeft += (i == 0? 0 : valuesList[i-1]);\n\n int outOfRange = sumLeft;\n for(int j = i+1;j < len; j++)\n {\n if(valuesList[j] -valuesList[i] > k)\n outOfRange += (valuesList[j] - valuesList[i]-k);\n }\n\n minDel = Math.Min(minDel, outOfRange);\n }\n\n return minDel;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
minimum-deletions-to-make-string-k-special | Python || Simple and Easy Solution | python-simple-and-easy-solution-by-vilap-q3ix | 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 | vilaparthibhaskar | NORMAL | 2024-07-02T09:44:09.332254+00:00 | 2024-07-02T09:44:09.332296+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n c = Counter(word)\n c = sorted(c.values())\n mn = math.inf\n p = 0\n for i in range(len(c)):\n temp = 0\n for j in range(len(c) - 1, i, -1):\n if c[j] <= (c[i] + k):break\n temp += (c[j] - c[i] - k)\n mn = min(mn, p + temp)\n p += c[i]\n return mn\n\n \n``` | 0 | 0 | ['Hash Table', 'Greedy', 'Sorting', 'Python3'] | 0 |
minimum-deletions-to-make-string-k-special | More Intuitive Dp approach | more-intuitive-dp-approach-by-divyam_1-cqhu | 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 | Divyam_1 | NORMAL | 2024-06-23T02:41:34.694949+00:00 | 2024-06-23T02:41:34.694979+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int solve(int i, int j , int k, vector<int>&freq, vector<vector<int>>&dp){\n if (i==j) return 0;\n if (dp[i][j]!=-1)return dp[i][j];\n if (freq[j]-freq[i] <=k) return 0;\n int back = freq[j]-(k+freq[i]) +solve(i, j-1, k, freq, dp);\n int front = freq[i] + solve(i+1, j, k, freq, dp);\n return dp[i][j] = min(front, back);\n }\n int minimumDeletions(string word, int k) {\n unordered_map<char,int>mpp;\n vector<int>freq;\n for (auto c : word) mpp[c]++;\n for(auto it : mpp) freq.push_back(it.second);\n sort(freq.begin(), freq.end());\n int n = freq.size();\n vector<vector<int>>dp(n, vector<int>(n, -1));\n return solve(0, n-1,k, freq, dp);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Solution explained with diagrams. | solution-explained-with-diagrams-by-nan-y6h97 | Approach\n\n\n# Code\n\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n counts = Counter(word)\n values = list(sorted | nan-do | NORMAL | 2024-06-21T04:04:12.567502+00:00 | 2024-06-21T04:04:12.567530+00:00 | 8 | false | # Approach\n\n\n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n counts = Counter(word)\n values = list(sorted(counts.values(), reverse=True))\n\n def f(i):\n if i < 0:\n return 0\n\n curr_ans = 0\n for x in range(i):\n curr_ans += max(0, values[x] - (values[i] + k))\n \n return min(curr_ans, f(i-1)+values[i])\n\n return f(len(values)-1)\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | 3 solutions | Greedy, DFS/Rec, Memoization (DP) | 3-solutions-greedy-dfsrec-memoization-dp-nmhq | Solution-1: Greedy (WA -- 688 / 732 TCs passed -- 93.98%)\n+ IDEA: At each stage, we\'re greedily picking the smallest required change. i.e either mn (min eleme | shahsb | NORMAL | 2024-06-17T05:37:16.729432+00:00 | 2024-07-02T03:35:51.635719+00:00 | 7 | false | # Solution-1: Greedy (WA -- 688 / 732 TCs passed -- 93.98%)\n+ **IDEA:** At each stage, we\'re greedily picking the smallest required change. i.e either `mn` (min element) or `mx-mn-k` (removing diff from max element).\n+ **NOTE:** Kindly note that this solution only passes 93.98% of TCs. Intention behind sharing this solution is to: 1) Make you aware why greedy doesn\'t work here 2) How I came to the final solution.\n+ Greedy solution doesn\'t work here because there would be cases where removing min element would cause the result to be greater. Hence we would have to consider all possibilities to decide the answer.\nI hope this helps!\n\t### Complexity:\n\t+ **Time:** O(26 ^ 2)\n\t+ **Space:** O(26) --> **O(1)**\n\n\n# Solution-2: DFS/Recursion (AC -- 732/732 TCs Passed. -- 100%)\n+ **IDEA:** Consider all possibilities. Try removing/deleting from both ends -- min end and max end. \n\t### Complexity:\n\t+ **Time:** O(2^26) --> **O(10^7)**\n\t+ **Space:** O(26) --> **O(1)**\n# Solution-3: Memoization (DP) -- (AC -- 732/732 TCs Passed. -- 100%)\n+ **IDEA:** Memoize/store the result so that we do not compute the same sub problem again and again.\n\t### Complexity:\n\t+ **Time:** O(26^2) \n\t+ **Space:** O(26^2)\n# CODE:\n\n```\nclass Solution {\npublic:\n // SOL-1: GREEDY -- WA -- 688 / 732 TCs passed -- 93.98%\n int minimumDeletions(string word, int k) \n {\n vector<int> a(26, 0);\n for ( const char& c: word )\n a[c-\'a\']++;\n \n // SOL-1: GREEDY -- WA -- 688 / 732 TCs passed -- 93.98%\n // return greedy(a, k);\n \n // SOL-2: dfs/rec -- TC: O(2^26) -> O(10^7), SC: O(26) -- 732/732 TCs Passed.\n // sort(a.begin(), a.end());\n // return dfs(a, k, 0, a.size()-1);\n \n // SOL-3: DP -- MEMOIZATION -- TOP DOWN DP -- TC: O(26^2), SC: O(26^2) -- 732/732 TCs Passed.\n sort(a.begin(), a.end());\n vector<vector<int>> dp(26, vector<int>(26, -1));\n return memo(a, k, 0, a.size()-1, dp);\n }\n\nprivate:\n // SOL-3: DP -- MEMOIZATION -- TOP DOWN DP -- TC: O(26^2), SC: O(26^2) -- 732/732 TCs Passed.\n int memo(vector<int> &a, const int &k, int i, int j, vector<vector<int>>&dp)\n {\n if ( i >= j )\n return 0;\n \n if ( a[i] == 0 )\n return dp[i][j] = memo(a, k, i+1, j, dp);\n \n if ( a[j] - a[i] <= k )\n return dp[i][j] = 0;\n \n if ( dp[i][j] != -1 )\n return dp[i][j];\n\n int ans1 = a[i] + memo(a, k, i+1, j, dp);\n int ans2 = a[j] - a[i] - k + memo(a, k, i, j-1, dp);\n return dp[i][j] = min(ans1, ans2);\n }\n \n // SOL-2: dfs/rec -- TC: O(2^26) -> O(10^7), SC: O(26) -- 732/732 TCs Passed.\n int dfs(vector<int> &a, const int &k, int i, int j)\n {\n if ( i >= j )\n return 0;\n \n if ( a[i] == 0 )\n return dfs(a, k, i+1, j);\n \n if ( a[j] - a[i] <= k )\n return 0;\n \n int ans1 = a[i] + dfs(a, k, i+1, j);\n int ans2 = a[j] - a[i] - k + dfs(a, k, i, j-1);\n return min(ans1, ans2);\n }\n\n // SOL-1: GREEDY -- WA -- 688 / 732 TCs passed -- 93.98%\n int greedy(vector<int> &a, const int &k)\n {\n int ans = 0;\n while ( true )\n {\n int mn = INT_MAX, mx = INT_MIN, mxi = 0, mni = 0;\n for ( int i=0; i<26; i++ ) {\n if ( a[i] != 0 ) {\n //mn = min(mn, a[i]);\n if ( a[i] <= mn ) {\n mn = a[i]; mni = i;\n }\n //mx = max(mx, a[i]);\n if ( a[i] >= mx ) {\n mx = a[i]; mxi = i;\n }\n }\n }\n\n if ( mn == INT_MAX || mx == INT_MIN )\n break;\n\n int diff = mx-mn;\n if ( diff <= k )\n break;\n else {\n if ( diff - k < mn ) {\n ans += diff-k;\n a[mxi] -= (diff-k);\n } else {\n ans += mn;\n a[mni] = 0;\n }\n } \n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Greedy', 'Depth-First Search', 'Recursion', 'Memoization', 'C'] | 0 |
minimum-deletions-to-make-string-k-special | TOO EASY DP | too-easy-dp-by-mohdibrahim12123-e5ki | Intuition\ndp\n\n# Approach\ndp\n\n# Complexity\n- Time complexity:\no(2626)\n\n- Space complexity:\no(2626)\n\n# Code\n\nclass Solution {\npublic:\n int hel | mohdibrahim12123 | NORMAL | 2024-06-16T17:41:26.270998+00:00 | 2024-06-16T17:41:26.271065+00:00 | 3 | false | # Intuition\ndp\n\n# Approach\ndp\n\n# Complexity\n- Time complexity:\no(26*26)\n\n- Space complexity:\no(26*26)\n\n# Code\n```\nclass Solution {\npublic:\n int helper(int i,int j,vector<int> &freq,int k,vector<vector<int>> &dp)\n {\n if(i==j || freq[j]-freq[i]<=k)\n return 0;\n if(dp[i][j]!=-1)\n return dp[i][j];\n \n int ans=min(freq[i]+helper(i+1,j,freq,k,dp),freq[j]-freq[i]-k+helper(i,j-1,freq,k,dp));\n return dp[i][j]=ans;\n }\n int minimumDeletions(string word, int k) {\n vector<int> freq(26,0);\n for(auto x:word)\n {\n freq[x-\'a\']++;\n }\n sort(freq.begin(),freq.end());\n vector<vector<int>> dp(26,vector<int> (26,-1));\n return helper(0,25,freq,k,dp);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | [Rust] Beats 100% -- it's not O(n^2) if you only have 26 letters | rust-beats-100-its-not-on2-if-you-only-h-tz7w | Intuition\nFirst thing, we need to count the number of frequency of each letter in word, and sort them so we can easily identify low frequencies and high freque | tiedyedvortex | NORMAL | 2024-06-15T14:10:31.713108+00:00 | 2024-06-15T14:10:31.713143+00:00 | 1 | false | # Intuition\nFirst thing, we need to count the number of frequency of each letter in word, and sort them so we can easily identify low frequencies and high frequencies.\n\nThen, when faced with a frequency distribution, we have two approaches to reduce it down to some range.\n\nOne option would be to keep the lowest-frequency letter as it is, and then reduce all frequencies that are too high down until they fit. For example, if our frequency array was [99, 99, 101] with k = 1, we could achieve this in one step by reducing 101 -> 100, because 99 + 1 == 100.\n\nThe other option is to drop the lowest-frequency letter entirely, and then repeat on the inner array. For example, if our frequency array is [1, 99, 101] with k =1 then it\'s best to drop the 1 to get [99, 101] and then reduce from 101 -> 100, getting to [99, 100] in two moves.\n\nBecause there are at most 26 letters in consideration, we can easily test all possibilities of number of dropped letters; no dropped letters, drop the lowest-frequency, drop the two lowest-frequency, etc. until we get to a point where the cost of dropping the (x) lowest letters exceeds the best-tested result so far.\n\n# Approach\nStore frequencies a byte array; this is stack-allocated, finite memory.\n\nThen take a slice into that memory of just the portion with positive probabilities to avoid unnecessary iterations, and incrementally reduce the slice window.\n\nKeep two running totals; the best total cost seen so far, and the cost of dropping the lowest-frequencey frequencies to get to the current frequencies slice. Early-exit once the drop cost would exceed the best-achieved cost.\n\n# Complexity\n- Time complexity: O(n) to scan the original word. After that, even in the worst case (for a word with all 26 letters that needs to drop 25 of them) we perform finitely many operations. If the \n\n- Space complexity: O(1), we only need a 26-size array and a few integers as working memory.\n\n# Code\n```\nimpl Solution {\n pub fn minimum_deletions(word: String, k: i32) -> i32 {\n let mut freqs = [0_i32; 26];\n for byte in word.bytes() {\n freqs[(byte-b\'a\') as usize] += 1;\n }\n freqs.sort_unstable();\n let left = {\n let mut left = 0;\n while left < 26 && freqs[left] == 0 {\n left += 1;\n }\n left\n };\n let mut freqs = &freqs[left..];\n\n let mut best = i32::MAX;\n let mut drop_cost = 0;\n while let Some(&lowest) = freqs.first() {\n let keep_lowest: i32 = freqs.iter().filter_map(|&freq| if lowest + k < freq {\n Some(freq - lowest - k)\n } else {\n None\n }).sum();\n best = best.min(drop_cost + keep_lowest);\n drop_cost += lowest;\n if drop_cost >= best {\n return best;\n }\n freqs = &freqs[1..];\n }\n\n // This will only be reached if word is empty,\n // or contains chars other than [a-z]\n 0\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
minimum-deletions-to-make-string-k-special | 3085. Minimum Deletions to Make String K-Special | 3085-minimum-deletions-to-make-string-k-4l5od | 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 | Priyankaaaaa | NORMAL | 2024-06-10T14:47:17.942656+00:00 | 2024-06-10T14:47:17.942686+00:00 | 5 | 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 minimumDeletions(String word, int k) {\n\n int res = Integer.MAX_VALUE;\n int[] freq = new int[26];\n int sumsofar = 0;\n for(char ch : word.toCharArray()){\n freq[ch - \'a\']++;\n }\n\n Arrays.sort(freq);\n for(int i=0;i<26;i++){\n int temp = sumsofar;\n for(int j=i+1;j<26;j++){\n temp += Math.max(0,freq[j]-freq[i]-k);\n }\n res = Math.min(res,temp);\n sumsofar += freq[i];\n }\n\n return res;\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | SImple solution | simple-solution-by-risabhuchiha-16h0 | \n\nclass Solution {\n Integer[][]dp=new Integer[26][26];\n public int minimumDeletions(String word, int k) {\n int[]a=new int[26];\n for(ch | risabhuchiha | NORMAL | 2024-06-09T01:54:39.259569+00:00 | 2024-06-09T01:54:39.259601+00:00 | 4 | false | \n```\nclass Solution {\n Integer[][]dp=new Integer[26][26];\n public int minimumDeletions(String word, int k) {\n int[]a=new int[26];\n for(char ch:word.toCharArray()){\n a[ch-\'a\']++;\n}\n//if(word.length()==1)return 0;\nint ans=0;\nArrays.sort(a);\nint j=0;\nwhile(a[j]==0)j++;\n //return a[\n \n int i=a.length-1;\n\n\n return f(j,i,a,k);\n }\n public int f(int i,int j,int[]a,int k){\n if(i==j)return 0;\n if(a[j]-a[i]<=k)return 0;\n if(dp[i][j]!=null)return dp[i][j];\n return dp[i][j]=Math.min(a[i]+f(i+1,j,a,k),a[j]-a[i]-k+f(i,j-1,a,k));\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | simple java solution | simple-java-solution-by-lavlesh_pandey-jtbh | 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 | lavlesh_pandey | NORMAL | 2024-06-08T08:16:52.981763+00:00 | 2024-06-08T08:16:52.981784+00:00 | 2 | 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 minimumDeletions(String word, int k) {\n int []arr=new int[26];\n for(int i=0;i<word.length();i++){\n char ch=word.charAt(i);\n arr[ch-\'a\']++;\n }\n int del=Integer.MAX_VALUE;\n for(int i=0;i<26;i++){\n int freq=arr[i];\n int delete=0;\n for(int j=0;j<26;j++){\n if(i==j){\n continue;\n }\n if(arr[j]<freq){\n delete+=arr[j]; \n }\n else if(Math.abs(arr[j]-freq)>k){\n delete+=Math.abs(arr[j]-freq-k); // itne charcters delete honge...\n }\n }\n del=Math.min(del,delete);\n }\n return del;\n }\n}\n``` | 0 | 0 | ['Array', 'String', 'Java'] | 0 |
minimum-deletions-to-make-string-k-special | ✅counting->DP || cPP | counting-dp-cpp-by-darkenigma-8con | \n# Code\n\nclass Solution {\npublic:\n\n int solve(vector<int>& arr,vector<vector<int>>& dp,int i,int j,int k){\n if(i==j || arr[j]-arr[i]<=k)return | darkenigma | NORMAL | 2024-06-04T18:13:16.628082+00:00 | 2024-06-04T18:13:16.628119+00:00 | 0 | false | \n# Code\n```\nclass Solution {\npublic:\n\n int solve(vector<int>& arr,vector<vector<int>>& dp,int i,int j,int k){\n if(i==j || arr[j]-arr[i]<=k)return 0;\n if(dp[i][j]!=-1)return dp[i][j];\n return dp[i][j]=min(arr[i]+solve(arr,dp,i+1,j,k),arr[j]-arr[i]-k+solve(arr,dp,i,j-1,k));\n }\n int minimumDeletions(string word, int k) {\n map<char,int>mp;\n for(char i:word){\n mp[i]++;\n }\n vector<int>arr;\n for(auto itr=mp.begin();itr!=mp.end();itr++)arr.push_back(itr->second);\n sort(arr.begin(),arr.end());\n int n=arr.size();\n vector<vector<int>>dp(n,vector<int>(n,-1));\n return solve(arr,dp,0,n-1,k);\n }\n};\n``` | 0 | 0 | ['Hash Table', 'String', 'Sorting', 'Counting', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | O(n)...bahu saras solutioon | onbahu-saras-solutioon-by-gungun16-rtlu | 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 | Gungun16 | NORMAL | 2024-05-16T04:41:08.991524+00:00 | 2024-05-16T04:41:08.991564+00:00 | 0 | 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 minimumDeletions(String word, int k) {\n /* STEP 1 : First get the frequencies of each charaacter.... */\n HashMap<Character, Integer> hm = new HashMap<>();\n int n = word.length();\n for (int i = 0; i < n; i++) {\n char ch = word.charAt(i);\n hm.put(ch, hm.getOrDefault(ch, 0) + 1);\n }\n System.out.println(" hm " + hm);\n /*\n * for each element go on and search... freq[j]-freq[i]> k => you\'ll have to\n * delete these\n * extra characters... freq[j]<freq[i] => akhuj delete kari nakho.. then check\n * for all such number of deleteions\n * for that element...\n */\n int min_del = n;\n List<Integer> arr = new ArrayList<>(hm.values());\n for (int i = 0; i < arr.size(); i++) {\n int freq_i = arr.get(i);\n int curr_del = 0;\n for (int j = 0; j < arr.size(); j++) {\n if (i == j) {\n continue;\n }\n int freq_j = arr.get(j);\n System.out.println(" freq_i : " + freq_i + " freq_j : " + freq_j);\n if (freq_j < freq_i) {\n System.out.println(" case 1");\n curr_del += freq_j;\n } else if (Math.abs(freq_j - freq_i) > k) {\n System.out.println(" case 2");\n curr_del += Math.abs(freq_j - freq_i - k);\n } else {\n System.out.println(" case 3 ");\n /*\n * it is a valid case so no need to worry.\n * => Math.abs(freq_j - freq_j) <= k\n */\n }\n System.out.println(" ---- " + " curr_del " + curr_del + " ---- ");\n }\n min_del = Math.min(min_del, curr_del);\n System.out.println(" curr_del : " + curr_del + " min_del : " + min_del);\n System.out.println("===============================");\n }\n\n return min_del;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | gujju_ben_ni_gamzzat # Bahu saras O(n) ma solution... | gujju_ben_ni_gamzzat-bahu-saras-on-ma-so-vc3a | Intuition\n Describe your first thoughts on how to solve this problem. \nDarek character ni frequency par jau 6u and then check karu 6u ke ae character ni frequ | Gungun16 | NORMAL | 2024-05-16T03:52:30.242011+00:00 | 2024-05-16T03:52:30.242042+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDarek character ni frequency par jau 6u and then check karu 6u ke ae character ni frequency jetli bija badha j characters ni frequency ne karvi hoi to su karvanu.\n\nSau pratham to tamare badha j characters ni frequecny ne calculate kari do and aene alag thi ek arraylist ma muki do... so you kind of get the hold of all the frequencies.\n\nEk min_del karine ek variable ne initalize kari do...\n\nHu su vicharu 6u ke f-k and f+k bane thai sake to case ne simplyfy karva mate tamare to [f,f+k] --> sudhin j karavni do and agar koi ni frequency is less than f to aene to akho j delete kari nakho\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPachi have todarek charcter mate bija darek character ni frequency ne modify ka....aevi ritna modify karo ke ae banne no difference to tmaro k na j equal hoi...\nbasically apdee to aevu try kariye 6e ke agar freq_i = 4 ...then we are trying to do freq_j = [4, 4+k]\n\n1. so agar jo freq_j < freq_i => aena j na badha j characters ne delete karido...\n2. agar Math.abs(freq_j- freq_i) > k => agar jo aemna vadhhe characters no difference is greater than k then we are going to delete the extra characters atle k sudhi to apde allow karisu ...\npachi aena pachi je pan hase ae to extra j kehvase ...= aene delete karvu padse.\n3. Math.abs(freq_i- freq_j) <= k ---> aggar jo avu kaik hoi to to yar aa to valid j caes 6e nathi vandho avano..\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTraverse through each and every character in the word...to get the count of frequency of each character...\n\n O(n) \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nLet\'s assume all the characters are present.... then it is at max\n O(26) = O(1)\n\n# Code\n```\nclass Solution {\n public int minimumDeletions(String word, int k) {\n /* STEP 1 : First get the frequencies of each charaacter.... */\n HashMap<Character, Integer> hm = new HashMap<>();\n int n = word.length();\n for (int i = 0; i < n; i++) {\n char ch = word.charAt(i);\n hm.put(ch, hm.getOrDefault(ch, 0) + 1);\n }\n System.out.println(" hm " + hm);\n /*\n * for each element go on and search... freq[j]-freq[i]> k => you\'ll have to\n * delete these\n * extra characters... freq[j]<freq[i] => akhuj delete kari nakho.. then check\n * for all such number of deleteions\n * for that element...\n */\n int min_del = n;\n List<Integer> arr = new ArrayList<>(hm.values());\n for (int i = 0; i < arr.size(); i++) {\n int freq_i = arr.get(i);\n int curr_del = 0;\n for (int j = 0; j < arr.size(); j++) {\n if (i == j) {\n continue;\n }\n int freq_j = arr.get(j);\n System.out.println(" freq_i : " + freq_i + " freq_j : " + freq_j);\n if (freq_j < freq_i) {\n System.out.println(" case 1");\n curr_del += freq_j;\n } else if (Math.abs(freq_j - freq_i) > k) {\n System.out.println(" case 2");\n curr_del += Math.abs(freq_j - freq_i - k);\n } else {\n System.out.println(" case 3 ");\n /*\n * it is a valid case so no need to worry.\n * => Math.abs(freq_j - freq_j) <= k\n */\n }\n System.out.println(" ---- " + " curr_del " + curr_del + " ---- ");\n }\n min_del = Math.min(min_del, curr_del);\n System.out.println(" curr_del : " + curr_del + " min_del : " + min_del);\n System.out.println("===============================");\n }\n\n return min_del;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Minimum prefix removal | minimum-prefix-removal-by-vokasik-u8ip | The long description asks us to find minimum number of chars to be removed so that the diff between any 2 frequencies in word <= k.\n2. Find frequencies with Co | vokasik | NORMAL | 2024-05-10T23:04:02.058579+00:00 | 2024-05-10T23:04:02.058598+00:00 | 5 | false | 1. The long description asks us to find **minimum** number of chars to be removed so that the diff between any 2 frequencies in `word` <= k.\n2. Find frequencies with Counter/whatever\n3. Now we need to remove minimum chars and satisfy the condition: `|any_freq - any_other_freq| <= k`\n\nLet\'s look at a few examples to figure out how to deal with the problem:\n\nword: `abbcccc` `k = 0`\nfreq:`1,2,4`\n\nWhat should we remove?\nOptions:\n- we can equalize all the values to minimum value `1`: `1,1,1` will cost us: `0 + 2-1 + 4-1 = 4`\n- we can remove `1` and equalize all the rest values to minimum value `2`: `0,2,2` will cost us: `1 + 2-2 + 4-2 = 3`. Which is better\n- we can remove `2` and equalize all the rest values to minimum value `1`: `1,0,1` will cost us: `0 + 2-0 + 4-3 = 3`. Which is also good.\n\nFrom the above:\n- it does not make sense to remove biggest numbers as it leads to more removals (greedy)\n- removing minimum value and equalizing suffix values to `x <= k` should be the optimzal strategy\n\nCounter example to **remove single minimum** value:\n\nword: `aabbcccccccccddddddddd` `k = 2`\nfreq:`2,2,9,9`\n\nWhat should we remove?\nOptions:\n- we can equalize all the values to minimum value `2`: `2,2,2,2` will cost us: `14`\n- we can remove the first `2` and equalize all the values to minimum value `2`: `0,2,2,2` will cost us: `16`\n- we can remove the first and second `2` and equalize all the values to minimum value `9`: `0,0,9,9` will cost us: `4`\n\nFrom the above:\n- we can see that it\'s best to remove the **minimum** prefix_sum and find **minimum** removals needed in the suffix\n\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n """\n k-special: |f[i] - f[j]| <= k 0 <= i,j < N\n \n ret min # chars to delete to make w k-special\n \n aabcaba k = 0\n \n 421 -> 111 -> 3+1=4\n 421 -> 22 = 2+1=3\n \n 124 -> 022\n 1235 -> 1233 -> 2\n \n 16 -> 06\n \n 129: 022=7 vs 111=9\n \n 2299 -> 0099=4 vs 2222=14 \n min(remove prefix + equalize <= k)\n """\n freq = Counter(word)\n freq = sorted(freq.values())\n N = len(freq)\n res = inf\n for i in range(N):\n prefix = sum(freq[:i] or [0])\n suffix = 0\n for j in range(i + 1, N):\n diff = freq[j] - freq[i]\n if diff > k:\n suffix += diff - k\n res = min(res, prefix + suffix)\n return res\n\t\t\n\t\t# which is the same as\n freq = sorted(Counter(word).values())\n N = len(freq)\n res = inf\n prefix = 0\n for i in range(N):\n res = min(res, prefix + sum(max(0, freq[j] - freq[i] - k) for j in range(i + 1, N)))\n prefix += freq[i]\n return res\n\n``` | 0 | 0 | ['Prefix Sum', 'Python', 'Python3'] | 0 |
minimum-deletions-to-make-string-k-special | Shortest, Easiest, Clean & Clear | To the Point & Beginners Friendly Approach (❤️ ω ❤️) | shortest-easiest-clean-clear-to-the-poin-657a | Code\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int>v(26,0);\n for(auto i:word)v[i-\'a\']++;\n i | Nitansh_Koshta | NORMAL | 2024-04-28T08:12:53.268313+00:00 | 2024-04-28T08:12:53.268339+00:00 | 2 | false | # Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n vector<int>v(26,0);\n for(auto i:word)v[i-\'a\']++;\n int y=INT_MAX;\n for(int i=0;i<v.size();i++){\n int x=0;\n for(int j=0;j<v.size();j++){\n if(i!=j&&v[j]<v[i])x+=v[j];\n else if(abs(v[i]-v[j])>k)x+=abs(v[i]-v[j])-k;\n }\n y=min(y,x);\n }\n return y;\n\n// if you like my approach then please UpVOTE o((>\u03C9< ))o\n }\n};\n```\n\n\n | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | images | notes | c++ | greedy | images-notes-c-greedy-by-rahullodhi12-ehl5 | Notes\n\n\n\n# Code\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int ans = word.length();\n vector<int> freq(26, | rahullodhi12 | NORMAL | 2024-04-22T12:39:43.270443+00:00 | 2024-04-22T12:39:43.270475+00:00 | 8 | false | # Notes\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int ans = word.length();\n vector<int> freq(26,0);\n for(char ch: word){\n freq[ch-\'a\']++;\n }\n\n for(int i=0;i<26;i++){\n int del=0;\n for(int j=0;j<26;j++){\n if(i==j) continue;\n\n if(freq[j]<freq[i]){\n del += freq[j];//del all freq of a particular character\n }\n else if(abs(freq[i]-freq[j])>k){\n del += abs(freq[i]-freq[j])-k;\n }\n }\n ans = min(ans,del);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Hash Table', 'String', 'Greedy', 'Sorting', 'Counting', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | O(N) Easiest java solution. | on-easiest-java-solution-by-marshadow54-z2o5 | 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 | marshadow54 | NORMAL | 2024-04-20T12:37:43.654390+00:00 | 2024-04-20T12:37:43.654435+00:00 | 3 | 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 minimumDeletions(String word, int k) {\n int answer = Integer.MAX_VALUE;\n int[] f = new int[26];\n for(int i = 0; i < word.length(); i++) {\n f[word.charAt(i) - \'a\'] += 1; \n }\n for(int i = 0; i < f.length; i++) {\n if(f[i] == 0) continue;\n int remove = 0;\n for(int j = 0; j < f.length; j++) {\n if(f[j] == 0) continue;\n if(f[i] > f[j]) remove += f[j];\n else if(Math.abs(f[i] - f[j]) > k) {\n remove += f[j] - f[i] - k;\n // remove += Math.min(Math.abs(f[i] - f[j]) - k, f[j]);\n }\n }\n answer = Math.min(answer, remove);\n }\n return answer;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-deletions-to-make-string-k-special | Move window start over frequencies, 94% speed | move-window-start-over-frequencies-94-sp-x7uh | image.png\n\n\n# Code\n\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n freq = list(Counter(word).values())\n ans = | evgenysh | NORMAL | 2024-04-17T15:20:10.753257+00:00 | 2024-04-17T15:20:10.753294+00:00 | 9 | false | image.png\n\n\n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n freq = list(Counter(word).values())\n ans = len(word)\n for start in set(freq):\n end = start + k\n ans = min(ans, sum((f - end if f > end else 0) if f >= start else f\n for f in freq))\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | Proof of correctness | proof-of-correctness-by-ram_raghav-byn8 | As suggested by the hint, the following result can be used to solve the problem.\n\n*\nLet $new\_word$ be a k-simple word formed after perfoming the minimum num | Ram_Raghav | NORMAL | 2024-04-13T23:55:59.339579+00:00 | 2024-04-14T00:03:28.318445+00:00 | 11 | false | As suggested by the hint, the following result can be used to solve the problem.\n\n****\nLet $new\\_word$ be a k-simple word formed after perfoming the minimum number of deletions from word. Then there exists a character $c$ in $new\\_word$ that is never deleted. i.e., its frequency in $new\\_word$ is equal to its frequency in $word$\n****\nAssuming that the above result, we can loop over each unique character in $word$ and assume it is the character $c$. Then we compute min deletions required under this assumption. The minimim number of deletions will be the minumum of all these cases.\n\nBut why is the result true?\n\nAssume to the contrary that there does not exist such a $c$. Then every character in $word$ must be deleted at least once to form new word.\n\nNow, contruct any other word, say $better\\_word$, formed by deleting the same characters from $word$ as $new\\_word$, but all character in $new\\_word$ are deleted one less time.\n\nFor example, if the frequencies of characters in $new\\_word$ are \n$$a: 3, b: 4, c: 5$$\nthen the frequencies of character in $better\\_word$ are \n$$a: 4, b: 5, c: 6$$\n\nNow we will show that $better\\_word$ is k-simple. This will result in a contradiction as the number of deletions required to form $better\\_word$ is strictly lesser than the deletions required to form $new\\_word$. Let $\\alpha$ and $\\beta$ be any two characters in $better\\_word$. Note that from our contruction of $better\\_word$ $\\alpha$ and $\\beta$ are also character in $new\\_word$. Now, as $$new\\_word$$ is k-simple, \n\n$|\\text{freq of }\\alpha \\text{ in } new\\_word - \\text{freq of }\\alpha \\text{ in } new\\_word| < k$\n$\\implies |\\text{freq of }\\alpha \\text{ in } new\\_word + 1 - (\\text{freq of }\\beta \\text{ in } new\\_word + 1)| < k$\n$\\implies |\\text{freq of }\\alpha \\text{ in } better\\_word - \\text{freq of }\\beta \\text{ in } better\\_word| < k$\n\nSince $\\alpha$ and $\\beta$ were arbitrary, $better\\_word$ is k-simple.\n\nHence the result must be true. \n\nThe following solution closely mirrors the approach described at the start \n\n# Code\n```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n freq = list(Counter(word).values())\n minDeletions = float("inf")\n \n for c in freq:\n deletions = 0\n for f in freq:\n if f > c + k:\n deletions += (f - c) - k\n elif f < c:\n deletions += f\n minDeletions = min(deletions, minDeletions)\n \n return minDeletions\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | sliding window python | sliding-window-python-by-russellleung-6w00 | class Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n \n counter=Counter(word)\n values=sorted(counter.values())\n | russellleung | NORMAL | 2024-04-10T03:44:45.261896+00:00 | 2024-04-10T03:44:45.261921+00:00 | 0 | false | class Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n \n counter=Counter(word)\n values=sorted(counter.values())\n i=0\n total=0\n ans=float("inf")\n for j in range(len(values)):\n while i<len(values) and values[i]-values[j]<=k:\n total+=values[i]\n i+=1\n \n ans=min(ans,len(word)-total- (values[j]+k)*(len(values)-i))\n total-=values[j]\n \n return ans | 0 | 0 | [] | 0 |
minimum-deletions-to-make-string-k-special | 👌Runtime 14 ms Beats 77.08% of users with Go | runtime-14-ms-beats-7708-of-users-with-g-kgdr | Code\n\nfunc minimumDeletions(word string, k int) int {\n\tfreq := make([]int, 26)\n\tfor _, ch := range word {\n\t\tfreq[ch-\'a\']++\n\t}\n\n\tsort.Ints(freq)\ | pvt2024 | NORMAL | 2024-04-09T01:20:26.343986+00:00 | 2024-04-09T01:20:26.344015+00:00 | 5 | false | # Code\n```\nfunc minimumDeletions(word string, k int) int {\n\tfreq := make([]int, 26)\n\tfor _, ch := range word {\n\t\tfreq[ch-\'a\']++\n\t}\n\n\tsort.Ints(freq)\n\tminDel := int(^uint(0) >> 1) // MaxInt\n\n\tfor i := len(freq) - 1; i >= 0; i-- {\n\t\ttrgt := freq[i]\n\t\tdels := 0\n\n\t\tfor _, f := range freq {\n\t\t\tif f > trgt+k {\n\t\t\t\tdels += f - (trgt + k)\n\t\t\t} else if f < trgt {\n\t\t\t\tdels += f\n\t\t\t}\n\t\t}\n\n\t\tminDel = min(minDel, dels)\n\t\tif minDel == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif minDel == int(^uint(0)>>1) {\n\t\treturn 0\n\t}\n\treturn minDel\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n``` | 0 | 0 | ['Go'] | 0 |
minimum-deletions-to-make-string-k-special | C++ | Greedy | c-greedy-by-pikachuu-79nr | Code\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int freq[26] = {0};\n for(int i = 0; i < word.size(); i++) {\n | pikachuu | NORMAL | 2024-04-05T16:43:15.847611+00:00 | 2024-04-05T16:43:15.847643+00:00 | 7 | false | # Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int freq[26] = {0};\n for(int i = 0; i < word.size(); i++) {\n freq[word[i] - \'a\']++;\n }\n int ans = INT_MAX;\n for(int i = 0; i < 26; i++) {\n int del = 0;\n for(int j = 0; j < 26; j++) {\n if(freq[j] < freq[i]) del += freq[j];\n else if(freq[j] > freq[i]) del += max(0, freq[j] - freq[i] - k);\n }\n ans = min(ans, del);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['String', 'Greedy', 'Counting', 'C++'] | 0 |
minimum-deletions-to-make-string-k-special | [C++][Prefix sum] | cprefix-sum-by-mumrocks-t70n | \nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n /*\n a->1 b->2 c->3 d->5\n */\n vector<int> cnt(26);\n | MumRocks | NORMAL | 2024-04-03T14:09:15.762038+00:00 | 2024-04-03T14:09:15.762066+00:00 | 2 | false | ```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n /*\n a->1 b->2 c->3 d->5\n */\n vector<int> cnt(26);\n for(const auto w: word) cnt[w-\'a\']++;\n \n vector<int> dp;\n for (int i=0;i<26;i++) if (cnt[i]>0) dp.push_back(cnt[i]);\n \n sort(dp.begin(),dp.end());\n \n vector<int> prefixSum(dp.size()+1);\n for (int i=0;i<dp.size();i++) prefixSum[i+1] = prefixSum[i] + dp[i];\n \n int ans=INT_MAX,ri=0,leftAdj=0,rightAdj=0;\n for(int i=0;i<dp.size();i++){\n //li = lower_bound(dp.begin(),dp.end(),dp[i]-k)-dp.begin();\n ri = upper_bound(dp.begin(),dp.end(),dp[i]+k)-dp.begin();\n leftAdj = prefixSum[i];\n rightAdj = prefixSum.back()-prefixSum[ri]-(dp[i]+k)*(dp.size()-ri);\n ans = min(ans,leftAdj + rightAdj);\n //cout << i << " " << dp[i] << " " << li << " " << ri << " " << leftAdj << " " << rightAdj << endl;\n }\n return ans;\n \n }\n};\n``` | 0 | 0 | [] | 0 |
minimum-deletions-to-make-string-k-special | Easy C++ Prefix sum + Greedy | easy-c-prefix-sum-greedy-by-parteek_code-w707 | \n\n# Code\n\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int n = word.size();\n if(n<=1) return 0;\n vecto | parteek_coder | NORMAL | 2024-04-03T04:39:01.506368+00:00 | 2024-04-03T04:39:01.506397+00:00 | 6 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int n = word.size();\n if(n<=1) return 0;\n vector<int>alpha(26,0);\n vector<int>prefix(26,0);\n for(auto ch: word){\n alpha[ch-\'a\']++;\n }\n\n sort(alpha.begin(),alpha.end());\n prefix[0] = alpha[0];\n for(int i=1;i<26;i++){\n prefix[i] = prefix[i-1]+alpha[i];\n }\n int sum = 0;\n for(int j=0;j<26;j++) {\n sum+=alpha[j];\n }\n int i=0;\n int ans = INT_MAX;\n\n while(alpha[i]==0){\n i++;\n }\n for(;i<25;i++){\n auto index = upper_bound(alpha.begin(),alpha.end(),alpha[i]+k) - alpha.begin();\n int cur = prefix[25] - prefix[index-1];\n if(i>0) cur+= prefix[i-1];\n cur-= (26-index)*(k+alpha[i]);\n ans = min(ans,cur);\n }\n ans = min(ans,sum-alpha[25]);\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-deletions-to-make-string-k-special | Python Medium | python-medium-by-lucasschnee-w2ac | \nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n c = Counter(word)\n arr = list(c.values())\n arr.sort()\n | lucasschnee | NORMAL | 2024-04-03T02:03:36.413365+00:00 | 2024-04-03T02:03:36.413416+00:00 | 9 | false | ```\nclass Solution:\n def minimumDeletions(self, word: str, k: int) -> int:\n c = Counter(word)\n arr = list(c.values())\n arr.sort()\n N = len(arr)\n \'\'\'\n [1, 2]\n \n can also make chars 0\n \'\'\'\n # median = arr[N//2]\n # if N % 2 == 0:\n # median = math.ceil((arr[N // 2] + arr[(N - 1) // 2]) / 2)\n # print(arr, k)\n \'\'\'\n NEW PROBLEM: \n \n given an array of nums and an integer k, what is the minimum number of decrements to make all numbers k apart (or a number can be 0)\n \n say we have a goal range[a, a + k] where we want all numbers inside, where a is an integer\n \n costs:\n if num < a: cost = num -> (we want to make num 0)\n \n if a <= num <= a + k: cost = 0\n \n if num > a + k: cost = num - (a + k)\n \n \n can we use binary search?\n \n \n \'\'\'\n best = 10 ** 20\n \n for a in arr:\n interval = [a, a + k]\n total = 0\n \n for v in arr:\n if v < interval[0]:\n total += v\n elif interval[0] <= v <= interval[1]:\n pass\n else:\n total += v - interval[1]\n \n best = min(best, total)\n \n \n \n \n return best\n \n``` | 0 | 0 | ['Python3'] | 0 |
minimum-deletions-to-make-string-k-special | scala solution | scala-solution-by-vititov-62bg | \nobject Solution {\n def minimumDeletions(word: String, k: Int): Int = {\n lazy val freqs = word.groupMapReduce(identity)(_ => 1)(_ + _).values.to(List)\n | vititov | NORMAL | 2024-03-30T20:59:23.984248+00:00 | 2024-03-30T20:59:23.984282+00:00 | 2 | false | ```\nobject Solution {\n def minimumDeletions(word: String, k: Int): Int = {\n lazy val freqs = word.groupMapReduce(identity)(_ => 1)(_ + _).values.to(List)\n freqs.distinct.map{f => freqs.collect{\n case g if g<f => g\n case g if g-f > k => g-f-k \n }.sum\n }.min\n }\n}\n``` | 0 | 0 | ['Scala'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.