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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-number-of-non-overlapping-palindrome-substrings
|
Look at this --You won't find it hard..(Dp+Memoization -C++ code)
|
look-at-this-you-wont-find-it-harddpmemo-dew6
|
Intuition\n Describe your first thoughts on how to solve this problem. \nFist of all i would say it doesn\'t have much beats but its alright,as my approach is s
|
manmeet_muskan
|
NORMAL
|
2023-10-27T10:16:38.134424+00:00
|
2023-10-27T10:16:38.134448+00:00
| 30 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFist of all i would say it doesn\'t have much beats but its alright,as my approach is something that will be naturally clicking for everybody who knows even abc of dynamic programming (i.e. inclusion or exclusion).\nIt is simply if i am currently at any index either i can include it in my substring(named temp check code).\nor i can exclude. if i include it my answer will be 1+ recursive call for next index and in case of exclusion we don\'t need to add 1 and just take the maximum of them.\nOne important thing is that for every start i am going in a for loop checking every next character.\nNow let\'s understand in the form of code that will make it more clear.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nlet\'s start with the base case:-\nSimply if we go out of bound we need to return 0,easy right?..\nif we have value stored in dp return that value.i.e.\nif(dp[i]!=-1)\nreturn dp[i];\nNext we have temp that will store the substring if we include a particular character and similarly we have answer that we need to maximize.\nNow we run a for loop from the current index to size of string and adding the character to temp.\nIf size of temp>=k and temp is a palindrome i.e.basically if both conditions mentioned in question are satisfied,then we have an option of include it.So,i sent a recursive call for next index i.e. (j+1) and +1 in find for inclusion and taking the maximum between calculated value and ans as discussed earlier.\nUnlike inclusion,exclusion is condition independent i.e. we can always have a choice of exclusion.So,in the very next line i have calculated the maximum of ans and excluded value.\nAnd finally stored the value in dp table and returned the answer.\nWasn\'t it easy?\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSome of you might think it is going to O(n^3) as i ranges from 0 to n and for every i we have a for loop so,it will be n^2 and in every loop if we are checking for palindrome(So, n^3).But you made a mistake bro/sis.\nThink? OK let me answer,it is only the single time every index gets visited.So,despite having a loop it\'s Order of n (if you didn\'t get it check and understand the complexity of dfs) and of course (O(n)) for palindrome checking.\nSo,Time Complexity--O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSimply we have a dp array So,it will take O(n) space and we have temp string that can take up to O(n) space but yeah it may extend up for every i.So, it may end up in O(n^2).\nSo,Space Complexity--O(n^2)\n\n# Code\n```\nclass Solution {\npublic:\n bool ispalindrome(string&s){\n int i=0,j=s.size()-1;\n while(i<j){\n if(s[i]!=s[j])\n return 0;\n i++;\n j--;\n }\n return 1;\n }\n int find(string &s,int k,int i,vector<int>&dp){\n if(i>=s.size())\n return 0;\n if(dp[i]!=-1)\n return dp[i];\n // cout<<"i this time "<<i<<endl;\n string temp;\n int ans=0;\n for(int j=i;j<s.size();j++){\n temp+=s[j];\n if(temp.size()>=k and ispalindrome(temp))\n ans=max(ans,1+find(s,k,j+1,dp));\n ans=max(ans,find(s,k,j+1,dp));\n }\n return dp[i]=ans;\n }\n int maxPalindromes(string s, int k) {\n vector<int> dp(s.size()+5,-1);\n int ans=find(s,k,0,dp); \n return ans;\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'Recursion', 'Memoization', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Java || Easy Solution || With Explanation || Better than 100%
|
java-easy-solution-with-explanation-bett-30qm
|
Intuition\nGreedy Algorithm\n\n# Approach\n1. Firstly, check for k length palindrome \n2. If K length is not found then go for k+1 length palindrome. \nWe only
|
chhavigupta095
|
NORMAL
|
2023-10-12T03:01:20.612557+00:00
|
2023-10-12T03:01:20.612574+00:00
| 30 | false |
# Intuition\nGreedy Algorithm\n\n# Approach\n1. Firstly, check for k length palindrome \n2. If K length is not found then go for k+1 length palindrome. \nWe only have to check for even length and odd length palindrome and keep increasing count.\n\n\n# Complexity\n- Time complexity:\nO(N*k)\n\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution {\n public int maxPalindromes(String s, int k) {\n int index=0, n= s.length(),res=0;\n while(index< n){\n if(index+k-1< n && isPalindrome(s, index, index+k-1)){\n index+=k;\n res++;\n\n } else if(index+k< n &&isPalindrome(s, index, index+k)){\n index+=k+1;\n res++;\n\n }else{\n index++;\n }\n }\n return res;\n \n }\n public boolean isPalindrome(String s , int begin , int end){\n while(begin<end){\n if(s.charAt(begin) != s.charAt(end)) return false;\n begin++;end--;\n }\n return true;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Recursion + Memoization (1D DP)
|
recursion-memoization-1d-dp-by-diwaakar8-igj0
|
Complexity\n- Time complexity:\n O (n * k)\n\n- Space complexity:\n O (n)\n\n# Code\n\nclass Solution {\npublic:\n int f (int i, int j, int &k, string
|
Diwaakar84
|
NORMAL
|
2023-08-08T13:50:52.997430+00:00
|
2023-08-08T13:57:15.905586+00:00
| 299 | false |
# Complexity\n- Time complexity:\n O (n * k)\n\n- Space complexity:\n O (n)\n\n# Code\n```\nclass Solution {\npublic:\n int f (int i, int j, int &k, string &s, vector <bool> &dp)\n {\n if (i < 0 || j >= s.size ())\n return 0; //Out of bounds base case\n\n if (s [i] != s [j] || dp [i] || dp [j])\n return 0; //Not a valid option if ith and jth char don\'t match or overlap with another already found palindrome\n\n if (j - i + 1 >= k)\n {\n for (int x = i; x <= j; x++)\n dp [x] = true;\n return 1; //Obtain a palindrome string of size at least k\n }\n\n return f (i - 1, j + 1, k, s, dp); //Recursive call\n }\n int maxPalindromes(string s, int k) {\n int cnt = 0;\n int n = s.size ();\n vector <bool> dp (n, false);\n\n for (int i = 0; i < n; i++)\n { \n if (!dp [i])\n cnt += f (i, i, k, s, dp); //Odd length palindrome\n if (i < n - 1 && (s [i] == s [i + 1]) && !dp [i] && !dp [i + 1])\n cnt += f (i, i + 1, k, s, dp); //Even length palindrome\n }\n return cnt;\n }\n};\n```
| 1 | 0 |
['String', 'Dynamic Programming', 'Greedy', 'Recursion', 'Memoization', 'C++']
| 1 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Simple Python Solution O(n) with explanation 🔥
|
simple-python-solution-on-with-explanati-pgtz
|
Approach\n\n\n\n\nPalindromic substring cannot overlap, this means\n\nmax_count(0, i) = max_count(0, j) + max_count(j, i)\n\nwhere 0 <= j <= i\n\nNow, \n\n we h
|
wilspi
|
NORMAL
|
2023-01-22T16:30:02.992961+00:00
|
2023-01-22T18:03:44.170882+00:00
| 158 | false |
# Approach\n\n\n\n\nPalindromic substring cannot overlap, this means\n\n`max_count(0, i) = max_count(0, j) + max_count(j, i)`\n\nwhere `0 <= j <= i`\n\nNow, \n\n* we have to maximise `max_count(0, j)` and `max_count(j, i)`\n * `max_count(0, j)` is a sub-problem of our equation (the DP way)\n * but how to solve for `max_count(j, i)` ?\n* lets simplify this \n * if `max_count(j, i)` can have value 0 or 1 \n * 1 in case `str[j:i+1]` is a palindrome, \n * we will only have to maximise `max_count(0, j)`\n * we can run two nested for-loops (for `i` and `j`) to solve the simplied dp equation \n * the time complexity is $$O(n^2)$$, and `n<=2000`, which means this could still give us TLE (Time Limit Exceeded)\n* lets simplify further for `max_count(j, i)`\n * first time we will get maximum `max_count(j, i)` value ie one when a palindrome subsequence ends at `i`\n * since we have the condition of min length `k`, we have to check if there is a palindrome with length `k` or `k+1` ending at `i`\n * `k` and `k+1` to cover for odd and even palindromes\n * any other palindrome greater than `k+1` and ending at `i` is already covered in previous iterations\n\n\n\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(n)$$\n\n\n# Code (`O(n)`)\n``` python []\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n\n n = len(s)\n\n def isPalindrome(i, j):\n if j < 0:\n return False\n\n str = s[j : i + 1]\n rev_str = s[i : j - 1 : -1] if j > 0 else s[i::-1]\n\n return str == rev_str\n\n def getMaxPalindromes():\n mem = [0] * n\n\n for i in range(k - 1, n):\n mem[i] = mem[i - 1] if i > 0 else 0\n\n if isPalindrome(i, i - k + 1):\n mem[i] = max(mem[i], mem[i - k] + 1)\n\n if isPalindrome(i, i - k):\n mem[i] = max(mem[i], mem[i - k - 1] + 1)\n\n return mem[n - 1]\n\n return getMaxPalindromes()\n```\n\n\n\n
| 1 | 0 |
['String', 'Dynamic Programming', 'Python', 'Python3']
| 1 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ Easy Solution | Two Pointer | Runtime 0 ms Beats 100%
|
c-easy-solution-two-pointer-runtime-0-ms-xbn5
|
Intuition\nGiven string contains a palindrome substring or not.\nLongest Palindromic Substring - Try to solve this question with two pointer approach.\n\n# Appr
|
abhinandan__22
|
NORMAL
|
2022-12-29T18:22:11.398951+00:00
|
2022-12-29T18:24:53.199692+00:00
| 217 | false |
# Intuition\nGiven string contains a palindrome substring or not.\n[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/) - Try to solve this question with two pointer approach.\n\n# Approach\nTraverse a string for every character of the string, inzilate two pointers (L and R), and move L to the left and R to the right till a[L] == a[R]. R-L+1>=k, then the substring from L to R has a length greater than or equal to k, and it is a palindrome.\n\n# Complexity\n- Time complexity:\nO(N*N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxPalindromes(string a, int k) {\n int n = a.size(), lowerBound = 0 ,oddL, oddR, oddFlag, evenL, evenR, evenFlag , ans =0, i=0;\n while(i<n){\n oddL = i;\n oddR = i;\n oddFlag = 0;\n while(oddL>=lowerBound&&oddR<n&&a[oddL]==a[oddR]){\n if(oddR-oddL+1>=k){\n oddFlag =1;\n break;\n }\n oddL--;\n oddR++;\n }\n evenL = i;\n evenR = i+1;\n evenFlag = 0;\n while(evenL>=lowerBound&&evenR<n&&a[evenL]==a[evenR]){\n if(evenR-evenL+1>=k){\n evenFlag = 1;\n break;\n }\n evenL--;\n evenR++;\n }\n if(evenFlag==0&&oddFlag==0) i++;\n else if(evenFlag==1&&oddFlag==1){\n ans++;\n lowerBound = min(oddR,evenR)+1;\n i = lowerBound;\n }\n else if(evenFlag==1){\n ans++;\n lowerBound = evenR+1;\n i = lowerBound;\n }\n else{\n ans++;\n lowerBound = oddR+1;\n i = lowerBound;\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['Two Pointers', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Breaking problem into sub problems and taking only k & k+1 length palindromic substrings
|
breaking-problem-into-sub-problems-and-t-cuh3
|
If we break down the problems into sub problems we can easily solve it\nFirst find all the palindromic substrings using gap strategy and while doing that keep t
|
mayur_madhwani
|
NORMAL
|
2022-11-15T01:24:23.285202+00:00
|
2022-11-15T01:24:23.285245+00:00
| 298 | false |
If we break down the problems into sub problems we can easily solve it\nFirst find all the palindromic substrings using gap strategy and while doing that keep the start and end indices of all the substrings that have length k and k+1\nWhy k and k+1, because the substrings with length k+2 will have strings of length k inside them So it\'ll be optimanl to just take substrings of length k only\nSame goes for k+1 length\n\nNow the problem comes down to [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) Remove minimum number of intervals so that all other are non overlaping\n\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution {\npublic:\n int maxPalindromes(string s, int k) {\n \n int n = s.size();\n \n vector<vector<bool>> dp(n, vector<bool> (n, false));\n \n vector<vector<int>> a;\n \n for(int g = 0 ; g < n ; g++){//g is the gap between i & j\n \n for(int i = 0, j = g ; j < n ; i++, j++){\n \n if(g == 0)\n dp[i][j] = true;\n else if(g == 1)\n dp[i][j] = s[i] == s[j];\n else \n dp[i][j] = ((s[i] == s[j]) && dp[i+1][j-1]);\n \n if(dp[i][j] && (g==k-1 || g==k))\n a.push_back({i,j});\n \n }\n \n }\n \n int count = 0;//count denotes the number of intervals we need to remove\n \n sort(a.begin(), a.end());\n \n int l = 0,r = 1;\n \n n = a.size();\n \n while(r < n){\n \n if(a[l][1] < a[r][0]){\n l = r;\n r++;\n }else if(a[l][1] <= a[r][1]){\n count++;\n r++;\n }else if(a[l][1] > a[r][1]){\n l = r;\n count++;\n r++;\n }\n \n }\n \n return a.size() - count;\n }\n};\n```
| 1 | 0 |
['C++']
| 1 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ ✅✅| Greedy Approach 🔥| Easy and Simplified | 2 Approach |
|
c-greedy-approach-easy-and-simplified-2-hsgld
|
\n# Solution 1\n\nclass Solution {\npublic:\n bool ispal(string s,int l,int r){\n while(l<r){\n if(s[l]!=s[r]){\n return fal
|
kunal0612
|
NORMAL
|
2022-11-13T15:15:10.489202+00:00
|
2022-11-13T15:15:10.489235+00:00
| 285 | false |
\n# Solution 1\n```\nclass Solution {\npublic:\n bool ispal(string s,int l,int r){\n while(l<r){\n if(s[l]!=s[r]){\n return false;\n }\n l++;\n r--;\n }\n return true;\n }\n int maxPalindromes(string s, int k) {\n int n=s.size();\n int ans=0;\n for(int i=0;i<n;i++){\n for(int j=i;j<n;j++){\n int len=(j-i)+1;\n if(len>=k and ispal(s,i,j)){\n ans++;\n i=j;\n break;\n }\n if(len>k+1){\n break;\n }\n }\n }\n return ans;\n }\n};\n```\n# Solution 2\n```\nclass Solution {\npublic:\n bool ispal(string s){\n int l=0;\n int r=s.size()-1;\n while(l<r){\n if(s[l]!=s[r]){\n return false;\n }\n l++;\n r--;\n }\n return true;\n }\n int maxPalindromes(string s, int k) {\n int n=s.size();\n int ans=0;\n string str="";\n int i=0,j=0,t=0;\n while(i<=n-k){\n j=i;\n str="";\n t=i+1;\n while(j<n){\n str+=s[j];\n if(str.size()>k+1){\n break;\n }\n if(str.size()>=k){\n if(ispal(str)){\n ans++;\n t=j+1;\n str="";\n }\n }\n j++;\n }\n i=t;\n }\n return ans;\n }\n};\n```\n
| 1 | 0 |
['C++']
| 1 |
maximum-number-of-non-overlapping-palindrome-substrings
|
[Python3] cutting short is always better than cutting long
|
python3-cutting-short-is-always-better-t-zmsr
|
If the minimum cutting length k==3, then we always find palindrome of length 3 or 4, even if the actual palindrome is much longer. Because long or short, each p
|
yuanzhi247012
|
NORMAL
|
2022-11-13T14:42:39.607242+00:00
|
2022-11-14T03:22:28.217643+00:00
| 301 | false |
If the minimum cutting length k==3, then we always find palindrome of length 3 or 4, even if the actual palindrome is much longer. Because long or short, each palindrome can only contribute +1 to the result, and short palindrome can offer more possibilities for the rest parts.\n\n**dp(i)** means the max number of valid palindromes before i.\nWe can either choose to cut a palindrome ended at i, or not.\nIf we don\'t cut, dp(i)=dp(i-1)\nIf we cut, then we can either cut a palindrome of length k, or length k+1. \ndp(i)=dp(i-k)+1\ndp(i)=dp(i-k-1)+1\n"+1" here is the contribution of the palindrome we cut.\n\nWe choose the biggest of the three ways as the result of dp(i).\nDon\'t cut palindrome longer than k+1 as discussed above.\n\nisPalin(i,j) indicates whether s[i:j+1] is a palindrome or not.\nUsing cached recursive "isPalin" function is much faster than iterative way, as we need to check all palindromes.\n\n```\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n @cache\n def isPalin(i,j):\n if i>=j: return True\n return s[i]==s[j] and isPalin(i+1,j-1)\n dp = [0]*len(s)\n for j in range(k-1,len(s)):\n dp[j]=dp[j-1]\n for i in [j-k+1,j-k]:\n if i>=0 and isPalin(i,j):\n dp[j]=max(dp[j],dp[i-1]+1)\n return dp[-1]\n```
| 1 | 0 |
[]
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
True O(n) - DP + Manacher
|
true-on-dp-manacher-by-durvorezbariq-pd54
|
We use Manacher to check if a substring is a palindrome in O(1)\n- Manacher(s) preprocessing is O(n)\n- palin(i,i+k) checks if s[i:i+k] is palindrome in O(1)\n-
|
durvorezbariq
|
NORMAL
|
2022-11-13T14:23:10.791816+00:00
|
2022-12-06T11:33:02.584263+00:00
| 39 | false |
We use Manacher to check if a substring is a palindrome in O(1)\n- `Manacher(s)` preprocessing is O(n)\n- `palin(i,i+k)` checks if `s[i:i+k]` is palindrome in O(1)\n- `dp` is `O(n)`\n\n```\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n def Manacher(s):\n T = \'$#\'+\'#\'.join(s)+\'#&\'\n P = [0]*len(T)\n C,R = 0,0\n for i in range(len(T)-1):\n if R > i: \n P[i] = min(R-i,P[2*C-i])\n while T[i+P[i]+1] == T[i-P[i]-1]:\n P[i] += 1\n if R < i+P[i]:\n C,R = i,i+P[i]\n return P[2:-2]\n \n def palin(i,j):\n if j > len(s): return False\n l = j-i\n c = 2*((i+j)//2)-(l%2==0)\n return P[c] >= l\n \n @cache\n def dp(i):\n if i+k > len(s): return 0\n val = dp(i+1)\n if palin(i,i+k): val = max(val,1+dp(i+k))\n if palin(i,i+k+1): val = max(val,1+dp(i+k+1))\n return val\n P = Manacher(s)\n return dp(0)\n```
| 1 | 0 |
['Dynamic Programming']
| 2 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ || Simple O(n) solution || Manacher's Algorithm
|
c-simple-on-solution-manachers-algorithm-l2lc
|
Pre-requisite: Learn about Manacher\'s algorithm\n\nclass Solution {\npublic:\n vector<int> manachers(string s){\n string str = "#";\n for(char
|
_Potter_
|
NORMAL
|
2022-11-13T05:41:21.566129+00:00
|
2022-11-13T05:42:06.365168+00:00
| 573 | false |
**Pre-requisite:** Learn about [Manacher\'s algorithm](https://cp-algorithms.com/string/manacher.html/)\n```\nclass Solution {\npublic:\n vector<int> manachers(string s){\n string str = "#";\n for(char ch: s){\n str += ch;\n str += "#";\n }\n int c = 0, r = 0;\n vector<int> P(str.size(), 0);\n\t\t\n for(int i=1; i<str.size()-1; i++){\n if(i <= r){\n int imirror = (2*c)-i;\n P[i] = min(P[imirror], r-i);\n }\n \n int j = i+P[i]+1, k = i-P[i]-1;\n while(j<str.size() && k>=0 && str[j] == str[k]){\n P[i]++;\n j++;\n k--;\n }\n if(k-1 > r){\n c = i;\n r = k-1;\n }\n }\n return P;\n }\n \n int maxPalindromes(string s, int k) {\n // Find the palindrome length centered around each index using manacher\'s algorithm\n vector<int> P = manachers(s);\n \n // Stores the ending index of the previous palindrome substring\n int prev = -1;\n \n int ans = 0;\n for(int i=0; i<P.size(); i++){\n int len = P[i];\n // Palindrome length centered around index i is less than k\n if(len < k){\n continue;\n }\n // Now, we try to take only smallest palindrome which is atleast k \n if(k%2 == 0){\n if(len%2 == 0){\n len = k;\n }\n else{\n len = k+1;\n }\n }\n else{\n if(len%2 == 0){\n len = k+1;\n }\n else{\n len = k;\n }\n }\n \n // Starting index of the current palindrome\n int start = (i-len)/2;\n \n // Overlapping with previous palindrome\n if(start <= prev){\n continue;\n }\n \n ans++;\n int end = start+len-1;\n prev = end;\n }\n\t\t\n return ans;\n }\n};\n```\n```\ncout << "Upvote the solution if you like it !!" << endl;\n```
| 1 | 0 |
['C', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Map + DP + Comments + Explanation!
|
map-dp-comments-explanation-by-whynesspo-81zj
|
Read the maxPalindromes function first.\n \nsolve function-> returns max number of non overlapping palindrome strings up to index currentIndx\n\n# Code\n\nclass
|
whynesspower
|
NORMAL
|
2022-11-13T05:11:17.606410+00:00
|
2022-11-13T05:11:17.606453+00:00
| 303 | false |
Read the maxPalindromes function first.\n \nsolve function-> returns max number of non overlapping palindrome strings up to index currentIndx\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<int>dp;\n //dp[i] stores the max number of non overlapping palindrome strings upto index i \n map<int,int>StartingPoint;\n // Let (i,j) be an element of the map\n // Then if a string ends with \'i\'th index, its starting point is \'j\'th index;\n \n bool IsPalindrome(int i, int j, string &s){\n while(i<=j){\n if(s[i]!=s[j]) return false;\n i++;\n j--;\n }\n return true;\n }\n \n int solve(int currentIndx){\n if(currentIndx<0) return 0;\n if(dp[currentIndx]!=-1) return dp[currentIndx];\n int startingIndx= StartingPoint[currentIndx];\n if(startingIndx==-1) return dp[currentIndx]=solve(currentIndx-1);\n dp[currentIndx]=max(1+solve(startingIndx-1), solve(currentIndx-1));\n return dp[currentIndx];\n }\n \n int maxPalindromes(string s, int k) {\n int n=s.size();\n dp.resize(n,-1);\n for(int i=n-1;i>=0;i--){\n StartingPoint[i]=-1;\n // -1 as a starting point indicates that no palindrome string ending at index \'i\' was found;\n for(int j=i-k+1;j>=0;j--){\n if(IsPalindrome(j, i, s)){\n // Greedily for every index we select the smallest possible palindromic string ending at that index\n // Thats why we break if Palindrome is found\n StartingPoint[i]=j;\n break;\n }\n }\n }\n solve(n-1);\n return dp[n-1];\n }\n};\n```\n\n
| 1 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ | DP
|
c-dp-by-coz_its_raunak-boqs
|
\n\nclass Solution {\npublic:\n \n int recc(vector<vector<int>>& adj, int i , int k, vector<int>& dpp)\n {\n if(i>=adj.size())\n retur
|
coz_its_raunak
|
NORMAL
|
2022-11-13T04:52:04.913501+00:00
|
2022-11-13T04:52:04.913534+00:00
| 214 | false |
```\n\nclass Solution {\npublic:\n \n int recc(vector<vector<int>>& adj, int i , int k, vector<int>& dpp)\n {\n if(i>=adj.size())\n return 0;\n \n if(dpp[i]!=-1)\n {\n return dpp[i];\n }\n int ans = 0;\n for(int j = i+k-1;j<adj.size();j++)\n {\n if(adj[i][j]==1)\n {\n ans = max(ans, recc(adj,j+1,k, dpp)+1);\n }\n }\n ans = max(ans, recc(adj,i+1,k, dpp));\n return dpp[i] = ans ;\n } \n\n int maxPalindromes(string s, int k)\n {\n int len = s.length();\n \n \n vector<vector<int>>dp(len, vector<int>(len,0));\n for(int i = 0;i<len;i++)\n {\n dp[i][i]= 1;\n }\n for(int i = len-2;i>=0;i--)\n {\n int st = len-1;\n for(int j = i;j>=0 && st;j--)\n {\n int x = j;\n int y = st;\n if(y-x==1)\n {\n if(s[x]==s[y])\n dp[x][y] = 1;\n }\n else if(s[x]==s[y] && dp[x+1][y-1]==1)\n {\n dp[x][y] = 1;\n }\n st--;\n \n }\n }\n vector<int>dpp(len,-1);\n return recc(dp,0,k, dpp);\n \n \n }\n};\n```
| 1 | 0 |
['Dynamic Programming']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Precalculate palindromic substrings and then solve independent intervals
|
precalculate-palindromic-substrings-and-ypqge
|
Intuition\n Describe your first thoughts on how to solve this problem. \n We already know a standard way to precalculate which substrings are palindromes in O(N
|
saikat93ify
|
NORMAL
|
2022-11-13T04:48:48.086869+00:00
|
2022-11-13T04:48:48.086906+00:00
| 167 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* We already know a standard way to precalculate which substrings are palindromes in $$O(N^2)$$ time. \n* Notice that intervals are independent of each other\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n* Let $$f(i)$$ be the maximum number of palindromic substrings ending at $$i$$. \n\n* $$f(i) = \\max(f(i - 1), 1 + f(j - 1)), \\forall j$$ such that $$S[j, i]$$ is a palindrome \n\n# Complexity\n- Time complexity: $$O(N^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n[GitHub](https://github.com/MathProgrammer/LeetCode/tree/master/Contests/Weekly%20Contest%20319)\n\n# Code\n```\nclass Solution {\npublic:\n int maxPalindromes(string S, int k) \n {\n vector <vector <int> > is_palindrome(S.size(), vector <int> (S.size(), 0)); \n for(int length = 1; length <= S.size(); length++)\n {\n for(int left = 0, right = left + length - 1; right < S.size(); left++, right++)\n {\n if(length == 1)\n {\n is_palindrome[left][right] = true;\n }\n else if(length == 2)\n {\n is_palindrome[left][right] = (S[left] == S[right]);\n }\n else\n {\n is_palindrome[left][right] = ( (S[left] == S[right])&is_palindrome[left + 1][right - 1]);\n }\n }\n }\n \n vector <int> maximum_palindromes_till(S.size(), 0);\n for(int i = k - 1; i < S.size(); i++)\n {\n maximum_palindromes_till[i] = is_palindrome[0][i];\n \n if(i >= 1)\n {\n maximum_palindromes_till[i] = max(maximum_palindromes_till[i - 1], is_palindrome[0][i]);\n }\n \n for(int j = i - k + 1; j > 0; j--)\n {\n if(is_palindrome[j][i])\n {\n //cout << "F(" << i << ") = max (" << maximum_palindromes_till[i] << ",";\n \n maximum_palindromes_till[i] = max(maximum_palindromes_till[i], 1 + maximum_palindromes_till[j - 1]);\n \n //cout << j - 1 << " = " << maximum_palindromes_till[j - 1] << "\\n";\n }\n }\n \n //cout << "F(" << i << ") = " << maximum_palindromes_till[i] << "\\n";\n }\n \n return maximum_palindromes_till[S.size() - 1];\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ simple non-DP solution, 0ms beats 100%
|
c-simple-non-dp-solution-0ms-beats-100-b-cxud
|
https://leetcode.com/submissions/detail/842418022/\nRuntime: 0 ms\nTime complexity: O(k\xB7n)\nSpace complexity: O(1)\n\nclass Solution {\npublic:\n int maxP
|
netvope
|
NORMAL
|
2022-11-13T04:34:37.641731+00:00
|
2022-11-13T04:43:25.721624+00:00
| 222 | false |
https://leetcode.com/submissions/detail/842418022/\nRuntime: 0 ms\nTime complexity: O(k\xB7n)\nSpace complexity: O(1)\n```\nclass Solution {\npublic:\n int maxPalindromes(string s, int k) {\n const int n = s.size();\n int count = 0;\n int len = 0; // the shortest prefix length having _count_ substrings\n for (int i = 0; i < n; ++i) {\n int new_len = INT_MAX;\n for (int j = 0; i-j >= len && i+j < n && s[i-j] == s[i+j]; ++j) {\n if (2*j + 1 >= k) {\n new_len = min(new_len, i + j + 1);\n break;\n }\n }\n for (int j = 0; i-j >= len && i+j+1 < n && s[i-j] == s[i+j+1]; ++j) {\n if (2*j + 2 >= k) {\n new_len = min(new_len, i + j + 2);\n break;\n }\n }\n if (new_len < INT_MAX) {\n len = new_len;\n ++count;\n }\n }\n return count;\n }\n};\n```
| 1 | 0 |
['Greedy', 'C']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
[Java] Rolling Hash + Dynamic Programming
|
java-rolling-hash-dynamic-programming-by-povp
|
\nclass Solution {\n private int[] record;\n private final int p = 31, mod1 = (int) (1e9 + 7);\n private int[] dp;\n public int maxPalindromes(Strin
|
nepo_ian
|
NORMAL
|
2022-11-13T04:11:40.273485+00:00
|
2022-11-13T04:11:40.273520+00:00
| 105 | false |
```\nclass Solution {\n private int[] record;\n private final int p = 31, mod1 = (int) (1e9 + 7);\n private int[] dp;\n public int maxPalindromes(String s, int k) {\n\n int n = s.length();\n record = new int[n];\n Arrays.fill(record, -1);\n util(s, n, k);\n\n dp = new int[n];\n Arrays.fill(dp, -1);\n return getMax(0, n);\n }\n\n private int getMax(int i, int n) {\n if (i >= n) return 0;\n\n if (dp[i] != -1) return dp[i];\n\n int ans = getMax(i + 1, n);\n if (record[i] != -1) ans = Math.max(ans, 1 + getMax(i + record[i], n));\n return dp[i] = ans;\n }\n\n private void util(String s, int n, int k) {\n for (int ii = 0; ii < n; ii++) {\n long hashff = 0, hashss = 0, power = 1;\n for (int i = ii; i < n; i++) {\n int ascii = s.charAt(i) - \'a\' + 1;\n hashff = (hashff + ((ascii * power) % mod1)) % mod1;\n hashss = (hashss * p) % mod1;\n hashss = (hashss + ascii) % mod1;\n power = (power * p) % mod1;\n\n if (hashff == hashss && (i - ii + 1) >= k) {\n record[ii] = i - ii + 1;\n break;\n }\n }\n }\n }\n}\n```
| 1 | 0 |
['Dynamic Programming', 'Rolling Hash', 'Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
simple linear dp (0(n2))
|
simple-linear-dp-0n2-by-aniketkumar1601-poqs
|
class Solution {\npublic:\n int maxPalindromes(string str, int k) {\n \n int n = str.length();\n \n int dp[n];\n \n
|
aniketkumar1601
|
NORMAL
|
2022-11-13T04:09:36.993668+00:00
|
2022-11-13T04:09:36.993695+00:00
| 197 | false |
class Solution {\npublic:\n int maxPalindromes(string str, int k) {\n \n int n = str.length();\n \n int dp[n];\n \n for(int i = 0; i < n; i++)\n {\n dp[i] = 0;\n }\n \n for(int i = n-k; i >= 0 ; i--)\n {\n deque<char> dq1;\n \n deque<char> dq2;\n \n for(int j = i; j <= n-1; j++)\n {\n dq1.push_front(str[j]);\n \n dq2.push_back(str[j]);\n \n if(dq1 == dq2 and j - i + 1 >= k)\n {\n dp[i] = 1 + (j + 1 < n ? dp[j+1] : 0);\n \n break;\n }\n }\n \n dp[i] = max(dp[i],i + 1 < n ? dp[i+1] : 0);\n }\n \n return dp[0];\n }\n};
| 1 | 0 |
['C++']
| 1 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Short C++ prefix xor solution
|
short-c-prefix-xor-solution-by-govind_pa-g9yt
|
\nclass Solution {\npublic:\n bool is_palin(int i, int j, string& s){\n while(i <= j){\n if(s[i] != s[j])\n return false;
|
govind_pandey
|
NORMAL
|
2022-11-13T04:05:06.265387+00:00
|
2022-11-13T04:05:06.265422+00:00
| 51 | false |
```\nclass Solution {\npublic:\n bool is_palin(int i, int j, string& s){\n while(i <= j){\n if(s[i] != s[j])\n return false;\n i++;\n j--;\n }\n return true;\n \n }\n int maxPalindromes(string s, int k) {\n int temp = 0,ans = 0;\n unordered_map<int,vector<int>>mp;\n if(k == 1)\n return s.size();\n for(int i = 0; i < s.size(); i++){\n temp = temp || (1 << (s[i] - \'a\'));\n int check = 0;\n if(mp.find(temp) != mp.end())\n for(int j = 0; j < mp[temp].size(); j++){\n \n if(__builtin_popcount(temp) <= 1 && abs(mp[temp][j] - i) + 1 >= k && is_palin(mp[temp][j],i,s)){\n ans++;\n mp.erase(mp.begin());\n check = 1;\n } \n }\n if(check == 0)\n mp[temp].push_back(i);\n }\n return ans;\n }\n};\n\n```
| 1 | 0 |
[]
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
easy short efficient clean code
|
easy-short-efficient-clean-code-by-maver-olgn
|
\nclass Solution {\ntypedef long long ll;\n#define vi(x) vector<x>\npublic:\nll n, k;\nstring s;\nvi(vi(ll))dp, memo;\nbool palin(ll l, ll r){\n if(l>=r){\n
|
maverick09
|
NORMAL
|
2022-11-13T04:04:04.428324+00:00
|
2022-11-13T04:04:04.428368+00:00
| 220 | false |
```\nclass Solution {\ntypedef long long ll;\n#define vi(x) vector<x>\npublic:\nll n, k;\nstring s;\nvi(vi(ll))dp, memo;\nbool palin(ll l, ll r){\n if(l>=r){\n return 1;\n }\n ll&ans=memo[l][r];\n if(ans==-1){\n ans=palin(l+1, r-1) && s[l]==s[r];\n }\n return ans;\n}\nll func(ll in, ll pre){\n if(in==n){\n return (in-pre>=k && palin(pre, in-1));\n }\n ll&ans=dp[pre][in];\n if(ans==-1){\n ll take=func(in+1, pre), dont=(in-pre+1>=k && palin(pre, in))+func(in+1, in+1);\n ans=max(take, dont);\n }\n return ans;\n}\n int maxPalindromes(const string&str, int K) {\n s=move(str), n=s.size(), k=K, dp.assign(n, vi(ll)(n, -1)), memo.assign(n, vi(ll)(n, -1));\n return func(0, 0);\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'Recursion', 'C']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
[c++] DP + sorting + greedy
|
c-dp-sorting-greedy-by-mble6125-cury
|
Approach\nstep 1. determin the substring s[i : j] is palindrome or not for all 0<=i, j< n.\nstep 2. record start point and end point of all palindrome substring
|
mble6125
|
NORMAL
|
2022-11-13T04:00:57.541577+00:00
|
2022-11-13T04:05:43.991989+00:00
| 258 | false |
# Approach\nstep 1. determin the substring s[i : j] is palindrome or not for all 0<=i, j< n.\nstep 2. record start point and end point of all palindrome substring whose size greater or eqaul to k. \nstep 3. sort it by the end points in increasing order.\nstep 4. traverse all intervals. Greedily pick current interval if it will not cause confliction.\n\n# Complexity\n- Time complexity:\ndetermin it is palindrome for all substring: O(n^2)\nsorting: O(nlog n)\n=> total O(n^2)\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxPalindromes(string s, int k) {\n if (k==1) return s.size();\n \n int n=s.size();\n vector<pair<int,int>> intervals;\n vector<vector<bool>> dp(n, vector<bool>(n, true));\n \n for (int diff=1; diff<n; ++diff) {\n for (int i=0, j=diff; j<n; ++i, ++j) {\n dp[i][j]=dp[i+1][j-1] && s[i]==s[j];\n \n if (dp[i][j] && diff+1>=k) intervals.push_back({i, j});\n }\n }\n \n sort(intervals.begin(), intervals.end(), compare);\n \n int res=0;\n for (int i=0, cur=-1; i<intervals.size(); ++i) {\n if (cur < intervals[i].first) {\n cur=intervals[i].second;\n ++res;\n }\n }\n \n return res;\n }\n \n static bool compare(pair<int,int>& a, pair<int,int>& b) {\n return a.second<b.second;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Top-Bottom DP explained
|
top-bottom-dp-explained-by-remedydev-mqej
|
ApproachTop-Down Dynamic Programming approach
We try to form a palindrome starting from every "i-th" index.
If we succeed, we call a recursion again to attempt
|
remedydev
|
NORMAL
|
2025-03-25T17:46:22.039582+00:00
|
2025-03-25T17:46:22.039582+00:00
| 3 | false |
# Approach
Top-Down Dynamic Programming approach
1. We try to form a palindrome starting from every "i-th" index.
2. If we succeed, we call a recursion again to attempt to form the next palindrome right after the current one.
3. We also try to skip the "start" index and attempt to form a larger answer starting from the next index (start+1).
# Complexity
- Time complexity:
$$O(n^2)$$
- Space complexity:
$$O(n)$$ (if k=1)
# Code
```java []
class Solution {
public int maxPalindromes(String s, int k) {
int[] dp=new int[s.length()];
Arrays.fill(dp,-1);
return dfs(s.toCharArray(),0,k,dp);
}
// Each dfs call returns maximum number of palindromes starting from "start" index
private int dfs(char[] s, int start, int k,int[] dp){
if(start==s.length) return 0;
if(dp[start]!=-1) return dp[start];
int ans=0;
// Try to form a palindrome
for( int i=start;i<s.length;i++){
if(i-start+1>=k && isPalindrome(s,start,i)){
ans=dfs(s, i+1, k, dp)+1; // once we got a palindrome we count it and try to form a next one
break; // since we need maximum amount of palindromes we STOP right here
}
}
return dp[start] = Math.max(ans, dfs(s, start+1, k, dp));
}
private boolean isPalindrome(char[] s, int i, int j){
while(i<j){
if(s[i]!=s[j]){
return false;
}
i++;j--;
}
return true;
}
}
```
| 0 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
scala dp
|
scala-dp-by-vititov-p7lp
| null |
vititov
|
NORMAL
|
2025-02-15T19:15:29.116061+00:00
|
2025-02-15T19:15:29.116061+00:00
| 2 | false |
```scala []
object Solution {
def maxPalindromes(s: String, k: Int): Int = {
val dp=Array.fill(s.length+1)(0)
@annotation.tailrec def check(i: Int, j:Int): Boolean =
(i>=j) || (s(i) == s(j) && check(i+1, j-1))
;var mx = 0; var i=0; while(i<s.length) {
;var j=i+k-1; while(j<s.length) {
mx = mx max dp((i-1) max 0)
if(check(i,j)) dp(j) = dp(j) max (mx+1)
j+=1
}
i+=1
}
dp.max
}
}
```
| 0 | 0 |
['Dynamic Programming', 'Scala']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
VERY simple recursive solution: $$O(n × k)$$
|
very-simple-recursive-solution-on-x-k-by-g0ea
|
IntuitionWe always prefer to take the shortest palindrome available, leaving more characters available to be in other palindromes. A greedy approach will work.W
|
adam-hoelscher
|
NORMAL
|
2025-02-07T23:47:14.272509+00:00
|
2025-02-07T23:47:14.272509+00:00
| 5 | false |
# Intuition
We always prefer to take the shortest palindrome available, leaving more characters available to be in other palindromes. A greedy approach will work.
We can organize our search by checking for palindromes at the beginning of the string.
# Approach
For each character in the string, check to see if it is the beginning of a palindrome of length $$k$$ or $$k+1$$ (in that order). If it is, add 1 and move the the first unused character in the string. If it is not, move to the next character.
The recursive implementation of this approach is incredibly easy to read. We check `s[0:k]`. If that fails, we check `s[0:k+1]`. If that also fails, we move on.
To simplify the palindrome check as much as possible, we start pointers on the first and last character and then move them in while the characters under them match. If they cross that means the substring was a palindrome.
# Complexity
- Time complexity: $$O(n×k)$$
If $$n$$ is the length of the string `s`, then we make up to $$2×n$$ checks for palindromes. Each check could take up to $$k/2$$ steps.
$$O(2×n) × O(k/2) = O(n × k)$$
- Space complexity: $$O(n)$$
Each `s[i]` takes constant space regardless of $$n$$. There can be up to $$n$$ recursive calls on the call stack.
$$O(1) × O(n) = O(n)$$
Putting the check in a loop can easily allow an iterative solution, which will take $$O(1)$$ space.
# Code
```golang []
func maxPalindromes(s string, k int) int {
// Base case: if s is empty there are no palindromes
if s == "" {
return 0
}
// Loop to test odd and even length palindromes
for par := range min(2, len(s)-k+1) {
// Start pointers on the outside
i, j := 0, k+par-1
// Iterate while the values match
for i <= j && s[i] == s[j] {
i, j = i+1, j-1
}
// If the pointers didn't cross no palindrome was found
if i < j {
continue
}
// Greedily take this palindrome and search the rest of the string
return 1 + maxPalindromes(s[k+par:], k)
}
// If no palindrome starts with s[0], move on to s[1]
return maxPalindromes(s[1:], k)
}
```
| 0 | 0 |
['Go']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Java | easy to understand | beats 100%
|
java-easy-to-understand-beats-100-by-dea-9soa
|
Understanding the Problem:Given a string s and an integer k, the goal is to find the maximum number of non-overlapping palindromic substrings in s, where each s
|
deadvikash
|
NORMAL
|
2025-01-24T12:41:49.248931+00:00
|
2025-01-24T12:41:49.248931+00:00
| 6 | false |
Understanding the Problem:
Given a string s and an integer k, the goal is to find the maximum number of non-overlapping palindromic substrings in s, where each substring has a length of at least k.
Solution Approach:
The solution uses an approach that expands around centers. It checks for both odd-length and even-length palindromes centered at each possible position in the string. The key to ensuring non-overlapping substrings is the prevLeft variable.
# Code
```java []
class Solution {
int k;
int len;
int prevLeft = Integer.MIN_VALUE; //Keeps track of the left boundary of the previously selected palindrome
public int maxPalindromes(String s, int k) {
len = s.length();
this.k = k;
int count = 0;
for(int i = 0; i < len; i++) {
count += checkPalindrom(s, i, i); // Check for odd length palindromes
count += checkPalindrom(s, i, i + 1); // Check for even length palindromes
}
return count;
}
private int checkPalindrom(String s, int left, int right) {
int count = 0;
boolean check = true;
while(left >= 0 && left > prevLeft && right < len && s.charAt(left) == s.charAt(right)) {
if(right - left + 1 >= k) { //Check if the length is greater than or equal to k
count++;
check = false; //Set check false so that we don't consider overlapping substrings
break; //Break the loop as we have found a valid palindrome
}
right++;
left--;
}
if(!check) prevLeft = right; //Update the prevLeft so that we don't consider overlapping substrings
return count;
}
}
```
| 0 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
2472. Maximum Number of Non-overlapping Palindrome Substrings
|
2472-maximum-number-of-non-overlapping-p-paz8
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
G8xd0QPqTy
|
NORMAL
|
2025-01-18T16:34:52.134144+00:00
|
2025-01-18T16:34:52.134144+00:00
| 7 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxPalindromes(self, S: str, k: int) -> int:
total_len, palindrome_ranges, last_position, palindrome_count = len(S), [], -float('inf'), 0
for idx in range(2 * total_len - 1):
left_bound = idx // 2
right_bound = left_bound + idx % 2
while left_bound >= 0 and right_bound < total_len and S[left_bound] == S[right_bound]:
if right_bound + 1 - left_bound >= k:
palindrome_ranges.append((left_bound, right_bound + 1))
break
left_bound -= 1
right_bound += 1
for start_pos, end_pos in palindrome_ranges:
if start_pos >= last_position:
last_position = end_pos
palindrome_count += 1
elif end_pos < last_position:
last_position = end_pos
return palindrome_count
```
| 0 | 0 |
['Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Maximum Number of Non-Overlapping Palindrome Substrings
|
maximum-number-of-non-overlapping-palind-32z4
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Naeem_ABD
|
NORMAL
|
2024-12-23T18:48:30.020366+00:00
|
2024-12-23T18:48:30.020366+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
var maxPalindromes = function(s, k) {
let res = 0;
const n = s.length;
for(let i = 0; i<= n-k; i++) {
if(isPalindrome(s, i, i+k-1)) {
res++;
i += k-1;
continue;
}
if(isPalindrome(s, i, i+k)) {
res++;
i +=k;
continue;
}
}
return res;
};
function isPalindrome( s, l, r) {
if(r >= s.length) {
return false;
}
while (l < r) {
if (s[l++] != s[r--]) {
return false;
}
}
return true;
}
```
| 0 | 0 |
['JavaScript']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Use greedy, no need for DP
|
use-greedy-no-need-for-dp-by-dharmenders-p9t8
|
Code
|
dharmendersheshma
|
NORMAL
|
2024-12-23T16:15:58.993215+00:00
|
2024-12-23T16:15:58.993215+00:00
| 4 | false |
# Code
```java []
class Solution {
int ans;
public int maxPalindromes(String s, int k) {
ans = 0;
int i = 0;
int n = s.length();
int left = 0;
while(i < n) {
int right = getRightSideOfPal(left, s, i, k);
if(right == -1) {
i++;
} else {
i = right;
left = right;
}
}
return ans;
}
private int getRightSideOfPal(int leftMin, String s, int i, int k) {
// for odd case, keep it before even case to handle k == 1 case
int left = i;
int right = i;
while(left >= leftMin && right < s.length() && s.charAt(left) == s.charAt(right)) {
if(right - left + 1 >= k) {
ans++;
return right + 1;
}
left--;
right++;
}
// for even case
left = i;
right = i + 1;
while(left >= leftMin && right < s.length() && s.charAt(left) == s.charAt(right)) {
if(right - left + 1 >= k) {
ans++;
return right + 1;
}
left--;
right++;
}
return -1;
}
}
```
| 0 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
✅DP || Python
|
dp-python-by-darkenigma-9ijg
|
Code
|
darkenigma
|
NORMAL
|
2024-12-13T05:29:49.203111+00:00
|
2024-12-13T05:29:49.203111+00:00
| 7 | false |
\n# Code\n```python3 []\nclass Solution:\n\n def check(self, i, k, n, dp2, dp):\n """\n Recursive function to find the maximum number of palindromic substrings \n of length at least k that can be extracted starting from index `i`.\n """\n # Base case: If we reach the end of the string, no more palindromes can be extracted\n if i == n:\n return 0\n \n # If this state has already been computed, return the cached result\n if dp2[i] != -1:\n return dp2[i]\n \n # Option 1: Skip the current character and move to the next index\n ans = self.check(i + 1, k, n, dp2, dp)\n \n # Option 2: Try to extract palindromic substrings starting from `i`\n for j in range(i + k - 1, n): # Only consider substrings of length >= k\n if dp[i][j]: # Check if s[i:j+1] is a palindrome\n # Count this palindrome and recursively solve for the remaining substring\n ans = max(ans, 1 + self.check(j + 1, k, n, dp2, dp))\n \n # Cache the result for the current state\n dp2[i] = ans\n return ans\n\n def maxPalindromes(self, s: str, k: int) -> int:\n """\n Main function to compute the maximum number of palindromic substrings \n of length at least k in the given string `s`.\n """\n n = len(s)\n \n # Step 1: Precompute palindrome information for all substrings\n dp = [[0 for i in range(n)] for j in range(n)] # dp[i][j] = 1 if s[i:j+1] is a palindrome\n for length in range(1, n + 1): # Length of the substring\n j = 0\n while j + length - 1 < n: # Ensure the end index is within bounds\n if j == j + length - 1:\n dp[j][j + length - 1] = 1 # Single character is always a palindrome\n elif j + 1 == j + length - 1 and s[j] == s[j + length - 1]:\n dp[j][j + length - 1] = 1 # Two characters form a palindrome if they are equal\n elif dp[j + 1][j + length - 2] == 1 and s[j] == s[j + length - 1]:\n dp[j][j + length - 1] = 1 # Longer substrings inherit palindrome status\n else:\n dp[j][j + length - 1] = 0 # Not a palindrome\n j += 1\n\n # Step 2: Use recursive function with memoization to find the result\n dp2 = [-1 for _ in range(n)] # Memoization array for recursive calls\n return self.check(0, k, n, dp2, dp) # Start from index 0 with palindromes of length >= k\n\n```
| 0 | 0 |
['Two Pointers', 'String', 'Dynamic Programming', 'Greedy', 'Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
100%
|
100-by-mythsky-bj63
|
Uhh.. not sure if this should be medium. \nThe key is: the length of palindromes can be either odd or even. If the shorter case is already fit, then we don\'t n
|
mythsky
|
NORMAL
|
2024-10-20T01:57:57.543685+00:00
|
2024-10-20T02:03:12.227049+00:00
| 4 | false |
Uhh.. not sure if this should be medium. \nThe key is: the length of palindromes can be either odd or even. If the shorter case is already fit, then we don\'t need to check for the longer one(save the letters for the next check).\n\nNote: \nthe minimum length have to be k, k can be either odd or even\nodd+1=even\neven+1=odd\nSo doesn\'t matter k is even or odd\n\n# Code\n```python3 []\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n idx=0\n output=0\n while(idx+k<=len(s)):\n if s[idx:idx+k]==s[idx:idx+k][::-1]:\n output+=1\n idx+=k\n elif s[idx:idx+k+1]==s[idx:idx+k+1][::-1]:\n output+=1\n idx+=k+1\n else:\n idx+=1\n\n return output\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Easy Iterative Dp Solution
|
easy-iterative-dp-solution-by-kvivekcode-m205
|
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
|
kvivekcodes
|
NORMAL
|
2024-10-10T07:44:34.705023+00:00
|
2024-10-10T07:44:34.705068+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```cpp []\nclass Solution {\npublic:\n int maxPalindromes(string s, int k) {\n int n = s.size();\n\n vector<vector<int> > isPalin(n, vector<int> (n));\n\n for(int i = 0; i < n; i++) isPalin[i][i] = 1;\n for(int i = 0; i < n-1; i++){\n if(s[i] == s[i+1]) isPalin[i][i+1] = 1;\n }\n\n\n for(int L = 3; L <= n; L++){\n for(int i = 0; i <= n-L; i++){\n int j = i+L-1;\n if(isPalin[i+1][j-1] == 0) continue;\n if(s[i] == s[j]) isPalin[i][j] = 1;\n }\n }\n\n vector<int> dp(n+1);\n\n int ans = 0;\n for(int i = 1; i <= n; i++){\n bool f = 0;\n for(int j = i - k; j >= 0; j--){\n if(isPalin[j][i-1]) f = 1;\n if(f) dp[i] = max(dp[i], dp[j] + 1);\n ans = max(ans, dp[i]);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
[C++] GENERATE OPTIMAL INTERVALS | INTUITIVE SOLUTION
|
c-generate-optimal-intervals-intuitive-s-u4c4
|
Complexity\n- Time complexity:\nO(n*n)\n\n- Space complexity:\nO(n)\n\n# Code\ncpp []\nclass Solution {\npublic:\n bool is_pal(string& s) {\n for (int
|
ahbar
|
NORMAL
|
2024-09-24T06:02:18.244954+00:00
|
2024-09-24T06:02:18.244999+00:00
| 4 | false |
# Complexity\n- Time complexity:\nO(n*n)\n\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool is_pal(string& s) {\n for (int i =0; i < s.size() / 2; i++) {\n if (s[i] != s[s.size() -1- i]) return false;\n }\n return true;\n }\n\n int maxPalindromes(string s, int k) {\n vector<pair<int, int>> p;\n // if a palindrome of length > k exists and then a palindrome of length < k also exists\n // but since we only want palindromes of size >= k\n // so we check for smallest possible palindromes of sizes k and k + 1\n // because if a palindrome of length k exists then \n // there must also be a sub palindrome of length k - 2 inside that palindrome\n for (int sz = k; sz <= k +1; sz++) {\n for (int i =0; i <= s.size() -k; i++) {\n string curr =s.substr(i, sz);\n if (is_pal(curr)) \n p.push_back({i, i + sz-1});\n }\n }\n \n\n // this problem now turns into "max number of intervals that can we can take" \n sort(p.begin(), p.end(), [](auto& p1, auto& p2) {\n return p1.second == p2.second ? p1.first < p2.first : p1.second < p2.second;\n }); \n\n int cnt =0;\n int r = -1;\n for (auto x: p) {\n // cout << x.first << " " << x.second << endl;\n if (x.first > r) {\n cnt++;\n r = x.second;\n }\n }\n\n return cnt; \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
eazy "o(n)" solution , Beats 60.00%
|
eazy-on-solution-beats-6000-by-ed_snowde-extg
|
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
|
Ed_SNOWDEN_Eliot
|
NORMAL
|
2024-09-17T12:45:08.352397+00:00
|
2024-09-17T12:45:08.352432+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: o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```csharp []\npublic class Solution {\n public int MaxPalindromes(string s, int k) {\n if(k==1) {return s.Length; }\n\n string other = s;\n char[] ss = other.ToCharArray();\n int counter = 0;\n string word1 = "";\n string word2 = "";\n int start = 0;\n int index = 1;\n\n while(other.Length != 0 && index < other.Length)\n {\n if(word1 == "" && word2 == "")\n {\n if(ss[index] == ss[index-1])\n {\n start = index;\n word2 = ss[index-1].ToString() + ss[index].ToString(); }\n\n if(index+1 < other.Length && ss[index+1] == ss[index-1])\n {\n word1 = ss[index].ToString();\n start = index; }\n }\n else\n {\n if(word1 != "" && start-(index-start) >= 0 && ss[start-(index-start)] == ss[index])\n { word1 = ss[start-(index-start)].ToString() + word1 + ss[index].ToString(); }\n else { word1 = ""; }\n\n if(word2 != "" && (start-1)-(index-start) >= 0 && ss[(start-1)-(index-start)] == ss[index])\n { word2 = ss[(start-1)-(index-start)].ToString() + word2 + ss[index].ToString(); }\n else { word2 = ""; }\n\n if(word1 == "" && word2 == "") { index = start; }\n }\n if(word2.Length >= k && (word2.Length <= word1.Length || word1=="" || word1.Length < k))\n {\n counter++;\n other = other.Substring(index+1);\n ss = other.ToCharArray();\n index = 0;\n word1 = "";\n word2 = "";\n }\n else if(word1.Length >= k && (word1.Length <= word2.Length || word2=="" || word2.Length < k))\n {\n counter++;\n other = other.Substring(index+1);\n ss = other.ToCharArray();\n index = 0;\n word1 = "";\n word2 = "";\n }\n index++;\n }\n return counter;\n }\n}\n```
| 0 | 0 |
['Two Pointers', 'String', 'Dynamic Programming', 'Greedy', 'C#']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
DP Solution.
|
dp-solution-by-arif2321-zqak
|
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
|
Arif2321
|
NORMAL
|
2024-08-25T07:29:24.614641+00:00
|
2024-08-25T07:29:24.614672+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```cpp []\nclass Solution {\npublic:\n int maxPalindromes(string s, int k) \n {\n int n = s.size();\n vector<vector<int>> ispal(n,vector<int>(n,0));\n for(int i = 0; i < n; i++)\n {\n ispal[i][i] = 1;\n }\n for(int r = 0; r < n; r++)\n {\n for(int l = r-1; l >= 0; l--)\n {\n if(s[l] == s[r] && (r-l == 1 || ispal[l+1][r-1]))\n {\n ispal[l][r] = 1;\n }\n }\n }\n vector<int> dp(n); \n for(int i = 0; i < n; i++)\n {\n dp[i] = (i ? dp[i-1] : 0);\n for(int j = i; j >= 0; j--)\n {\n if(i-j+1 >= k && ispal[j][i])\n {\n dp[i] = max(dp[i],1 + (j ? dp[j-1] : 0));\n }\n }\n } \n return dp[n-1]; \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Best Answer without any knowledge of Dp simple approach easy no space
|
best-answer-without-any-knowledge-of-dp-jr4e4
|
Intuition\nThe intuition behind the approach is based on the fact that if a larger palindrome (longer than k+1) exists, then smaller palindromic substrings with
|
MadhavGarg
|
NORMAL
|
2024-08-17T23:09:16.021022+00:00
|
2024-08-17T23:14:35.335503+00:00
| 4 | false |
# Intuition\nThe intuition behind the approach is based on the fact that if a larger palindrome (longer than `k+1`) exists, then smaller palindromic substrings within it can be found by incrementally checking lengths `k` and `k+1`.\n\n### Example\nLet\'s consider the string `s = "abaxyzyxba"` and let `k = 4`.\n\n1. **Checking Length `k = 4`:**\n - Start by checking the substring `"abax"` (from index `0` to `3`).\n - `"abax"` is not a palindrome.\n\n2. **Checking Length `k+1 = 5`:**\n - Next, check the substring `"abaxy"` (from index `0` to `4`).\n - `"abaxy"` is not a palindrome.\n\n3. **Increment the Pointer (`i++`) and Check Again:**\n - Now, check the substring `"baxyz"` (from index `1` to `5`).\n - `"baxyz"` is not a palindrome.\n\n4. **Continue Incrementing:**\n - Check `"axyzy"` (from index `2` to `6`).\n - `"axyzy"` is not a palindrome.\n\n5. **Finally, Find a Larger Palindrome:**\n - Now, check `"xyzyx"` (from index `3` to `7`), which is a palindrome of length `5`.\n - Since `xyzyx` is a palindrome, you might wonder if we could have identified a smaller palindrome earlier.\n - In this case, notice that by removing the first and last characters from `"xyzyx"`, you get the substring `"yzy"` (from index `4` to `6`), which is also a palindrome of length `3`.\n - Although `"yzy"` is smaller, it is not within the original check window (we didn\u2019t check for `k = 3`). Instead, the algorithm moves to the next potential palindrome by incrementing the index.\n\n6. **Key Insight:**\n - If `"xyzyx"` (a palindrome of length `5`) is found, the algorithm could have skipped smaller checks. However, by focusing on `k` and `k+1`, we prioritize smaller palindromes first, ensuring they are not missed.\n\n### Conclusion:\nBy focusing on `k` and `k+1`, the approach ensures that the smallest palindromic substrings are found first, and larger palindromes that may encompass these smaller ones are naturally covered as the pointer advances. Even if a larger palindrome is found, the smaller one within it would have already been identified through earlier checks. This strategy ensures optimal coverage of the string with non-overlapping palindromic substrings.\n\n\n# Approach\n1. **Iterative Check**: Start iterating over the string from the beginning. For each position, check if the substring starting from that position of length `k` is a palindrome.\n2. **Skip if Palindrome Found**: If a palindrome of length `k` is found, increment the count and move the pointer by `k` to avoid overlapping. If a palindrome of length `k+1` is found, increment the count and move the pointer by `k+1`.\n3. **Single Character Skip**: If neither of the above substrings is a palindrome, move the pointer by 1 to check the next possible substring.\n4. **Return the Count**: Once the iteration is complete, return the total count of palindromic substrings found.\n\n# Complexity\n- Time complexity:\nThe time complexity is $$O(n \\times k)$$ where `n` is the length of the string and `k` is the length of the substring being checked. For each starting position in the string, checking if a substring is a palindrome takes `O(k)` time. The loop runs `O(n)` times, leading to a total time complexity of $$O(n \\times k)$$\n\n- Space complexity:\nThe space complexity is $$O(1)$$ as the solution only uses a constant amount of extra space for variables. The function `ispalin` operates in-place and does not require additional space proportional to the input size.\n\n# Code \n```\nclass Solution {\n public int maxPalindromes(String s, int k) {\n int n=s.length();\n int i=0,c=0;\n while(i<n-k+1)\n {\n if(ispalin(s.substring(i,i+k)))\n {\n c+=1;\n i+=k;\n }\n else if(i+k+1<=n && ispalin(s.substring(i,i+k+1)))\n {\n c+=1;\n i+=k+1;\n }\n else\n {\n i+=1;\n }\n }\n return c;\n \n }\n boolean ispalin(String s)\n {\n int i=0,j=s.length()-1;\n while(i<j)\n {\n if(s.charAt(i++)!=s.charAt(j--))\n {\n return false;\n\n }\n }\n return true;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
is it easy to understand this way !!!
|
is-it-easy-to-understand-this-way-by-san-x9bt
|
Intuition\n Describe your first thoughts on how to solve this problem. \n \n# Approach\n Describe your approach to solving the problem. \n - we go for every
|
sanchari0_1
|
NORMAL
|
2024-08-02T05:25:22.538392+00:00
|
2024-08-02T05:25:22.538418+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 - we go for every index and check whether there is a palindrome starting with idx and has minimum length k . \n - we need to make sure the palindrome we are choosing are not overlapping .\n - so if we have a palindrome of length l>k we would try to consider palindrome of smaller length , for example "aabbbaaa" , k = 3 , here if we choose palindrome starting from 0th index our count would only be one but if we instead choose "bbb" and "aaa" then count = 2 (max non overlapping ).\n - with this u can check the code and can understand why there is ans1 and ans2 and not greedy .\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#include <iostream>\n#include <string>\n#include <unordered_set>\n\nusing namespace std;\n\nclass Solution {\npublic:\n bool isPalindrome(const string &s) {\n int st = 0, en = s.length() - 1;\n while (st <= en) {\n if (s[st] != s[en]) {\n return false;\n }\n st++;\n en--;\n }\n return true;\n }\n\n int solve(const string &s, int k, int idx, vector<int>&dp) {\n int n = s.length();\n if (idx >= n) {\n return 0 ;\n }\n \n if(dp[idx]!=-1){\n return dp[idx];\n }\n\n string t = "";\n int j = -1;\n for (int i = idx; i < n; ++i) {\n t += s[i];\n if (t.length() >= k && isPalindrome(t)) {\n j = i+1 ; break;\n }\n }\n\n // Proceed to the next starting index\n int ans1= INT_MIN ; int ans2 = INT_MIN ;\n\n // it means there is a palindrome starting with index idx \n if(j!=-1){\n ans1 = 1 + solve(s,k,j,dp);\n }\n // whether there is a palindrome or not we choose not to include the index idx\n ans2 = solve(s, k, idx+1, dp);\n\n dp[idx] = max(ans1 , ans2);\n return dp[idx] ; \n \n }\n\n int maxPalindromes(string s, int k) {\n int n = s.length();\n vector<int>dp(n,-1);\n return solve(s, k, 0,dp);\n }\n};\n\n```
| 0 | 0 |
['Dynamic Programming', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ DP O(n^2)
|
c-dp-on2-by-airusian2-60zh
|
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
|
AirusIan2
|
NORMAL
|
2024-07-30T02:23:51.245412+00:00
|
2024-07-30T02:23:51.245443+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 maxPalindromes(string s, int k) {\n int n = s.length();\n vector<int> dp(n+1);\n vector<vector<bool>> p(n+1, vector<bool>(n+1));\n s = "#" + s;\n for(int i = 1 ; i <= n ; i++){\n for(int j = 1 ; j <= i ; j++){\n if(s[i] == s[j] && (i - j <= 2 || p[j+1][i-1])){\n p[j][i] = true;\n if(i - j + 1 >= k){\n dp[i] = max(dp[i], dp[j - 1] + 1);\n }\n }\n else{\n dp[i] = max(dp[i], dp[i-1]);\n }\n\n }\n }\n return dp[n];\n\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ With Palindrome Length Array
|
c-with-palindrome-length-array-by-__amri-dlan
|
Intuition\nFirst we create a palindromeLength Array starting at each index i. And use this array to find disjoint subarrays of length = palindromeLength[i]\n\n#
|
__amrit__saha__
|
NORMAL
|
2024-07-22T13:32:39.873717+00:00
|
2024-07-22T13:32:39.873747+00:00
| 1 | false |
# Intuition\nFirst we create a palindromeLength Array starting at each index i. And use this array to find disjoint subarrays of length = palindromeLength[i]\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\n#define v vector<int>\n\nclass Solution {\npublic:\n void print(v &arr) {\n for (int x : arr) {\n cout << x << " ";\n }\n cout << "\\n";\n }\n\n void populatePalindromeLengthSingle(string &s, v &palLength, int k) {\n int n = s.length();\n for (int i=0; i<n; i++) {\n int l = i, r = i;\n while (l>=0 && r<n && s[l]==s[r]) {\n palLength[l] = max(palLength[l], r-l+1);\n if (r-l+1 >= k) {break;}\n l--;\n r++;\n }\n }\n }\n\n void populatePalindromeLengthDouble(string &s, v &palLength, int k) {\n int n = s.length();\n for (int i=0; i<n-1; i++) {\n int l = i, r = i+1;\n while (l>=0 && r<n && s[l]==s[r]) {\n if (palLength[l] >= k && r-l+1 >= k) {\n palLength[l] = min(palLength[l], r-l+1);\n } else {\n palLength[l] = max(palLength[l], r-l+1);\n }\n if (r-l+1 > k) {break;}\n l--;\n r++;\n }\n }\n }\n\n int findMaxNonOverlappingCount(v &palLength, int k) {\n int n = palLength.size();\n v dp(n+1, 0);\n for (int i=n-1; i>=0; i--) {\n int palLen = palLength[i];\n if (palLen < k) {\n dp[i] = dp[i+1];\n } else {\n dp[i] = max(dp[i+1], 1+dp[i+palLen]);\n }\n }\n return dp[0];\n }\n\n int maxPalindromes(string s, int k) {\n int n = s.length();\n\n v palindromeLength(n, 1);\n populatePalindromeLengthSingle(s, palindromeLength, k);\n populatePalindromeLengthDouble(s, palindromeLength, k);\n\n return findMaxNonOverlappingCount(palindromeLength, k);\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Greedy dp
|
greedy-dp-by-fustigate-0gfa
|
Intuition\nsince substrings cannot overlap and we want as many palindromes as possible, it\'s best to only find palindromes with length of k or k + 1 (to accoun
|
Fustigate
|
NORMAL
|
2024-07-18T03:59:08.522193+00:00
|
2024-07-18T03:59:08.522225+00:00
| 11 | false |
# Intuition\nsince substrings cannot overlap and we want as many palindromes as possible, it\'s best to only find palindromes with length of k or k + 1 (to account for both even and odd length palindromes).\n\n# Code\n```python\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n def pal(i, j): \n if j > len(s) : return False \n return s[i:j] == s[i:j][::-1] \n \n @lru_cache(None) \n def dfs(i): \n if i + k > len(s) : return 0 \n m = dfs(i+1) \n if pal(i,i+k): \n m = max(m, 1 + dfs(i+k)) \n if pal(i,i+k+1): \n m = max(m, 1 + dfs(i+k+1)) \n return m \n return dfs(0)\n```
| 0 | 0 |
['Dynamic Programming', 'Greedy', 'Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Python (Simple DP)
|
python-simple-dp-by-rnotappl-yrut
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rnotappl
|
NORMAL
|
2024-07-16T12:27:26.255026+00:00
|
2024-07-16T12:27:26.255053+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 def maxPalindromes(self, s, k):\n n = len(s)\n\n @lru_cache(None)\n def function(i):\n if i >= n:\n return 0 \n\n max_val = function(i+1)\n\n if i+k <= n:\n if s[i:i+k] == s[i:i+k][::-1]:\n max_val = max(max_val,1+function(i+k))\n\n if i+k+1 <= n:\n if s[i:i+k+1] == s[i:i+k+1][::-1]:\n max_val = max(max_val,1+function(i+k+1))\n\n return max_val\n\n return function(0)\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
ap
|
ap-by-ap5123-lfff
|
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
|
ap5123
|
NORMAL
|
2024-07-08T19:41:59.523270+00:00
|
2024-07-08T19:41:59.523303+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 {\npublic:\n\n vector<vector<bool>> is_palindrome;\n vector<vector<bool>> is_calculated;\n \n bool p (string&s,int st, int ed) {\n if (st >= ed) return true;\n if (is_calculated[st][ed]) return is_palindrome[st][ed];\n \n is_calculated[st][ed] = true;\n \n if (s[st] == s[ed])\n is_palindrome[st][ed] = p(s,st+1, ed-1);\n else \n is_palindrome[st][ed] = false;\n \n return is_palindrome[st][ed];\n }\nint k1(int ind,int k,string&s,vector<int> &dp)\n{\n if(ind>=s.size())return 0;\n if(dp[ind]!=-1)return dp[ind];\n int ans=ans=k1(ind+1,k,s,dp); \n for(int i=ind+k-1;i<s.size();i++)\n {\n //cout<<p(s,ind,i)<<" "<<ind<<" "<<i<<endl;\n if(p(s,ind,i))ans=max(ans,1+k1(i+1,k,s,dp));\n }\n \n return dp[ind]=ans;\n}\n int maxPalindromes(string s, int k) {\n vector<int> dp(s.size(),-1);\n int n=s.size();\n is_palindrome.resize(n, vector<bool>(n, false));\n is_calculated.resize(n, vector<bool>(n, false));\n vector<vector<int>> dp1(s.size(),vector<int>(s.size(),-1));\n return k1(0,k,s,dp);\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Simple c++
|
simple-c-by-khurkhur-9sk6
|
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
|
khurkhur
|
NORMAL
|
2024-06-04T23:12:22.521641+00:00
|
2024-06-04T23:12:22.521663+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 {\npublic:\n int maxPalindromes(string s, int k) {\n if (k == 1) return s.size();\n\n int res = 0;\n\n int j = 0;\n int i = 0;\n while (i < s.size()) {\n if (i - j < k-1) {\n i = j + (k-1);\n continue; \n }\n\n bool ispal = false;\n for (int j2 = j; j2 <= i-k+1; ++j2) {\n ispal = true;\n for (int i1 = i, j1 = j2; i1 >= j1; --i1, ++j1) {\n if (s[i1] != s[j1]) {\n ispal = false;\n break;\n }\n }\n if (ispal) break;\n }\n\n if (ispal) {\n ++res;\n j = i+1;\n }\n ++i;\n }\n\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
[Python3] O(n) solution
|
python3-on-solution-by-coder-256-o1yl
|
Intuition\n Describe your first thoughts on how to solve this problem. \nUse Manacher\'s algorithm to calculate the max palindrome size centered at each letter
|
coder-256
|
NORMAL
|
2024-06-01T05:23:05.425381+00:00
|
2024-06-01T05:31:46.654083+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Manacher\'s algorithm to calculate the max palindrome size centered at each letter (odd-length palindromes) and centered between two letters (even-length palindromes). To make this easier, we convert e.g. "abc" to "|a|b|c|", and store this in `sp`.\n\nFor each palindrome centered at `sp[ip]` with length $p\\ge k$, we can simply update $dp[ip+p] = \\max (dp[ip+p], dp[ip-p]+1)$.\n\nHowever note that we need to use $k+1$ in place of $k$ if $p$ and $k$ have different parity (for example, given "abba" and $k=3$, we can take $p=4$ since it\'s the shortest even-length palindrome that still has length $\\ge k$). In the code, this is implemented simply using bitwise operations on bit 0 (see `l = (ip-k-2)|1`, `r = (ip+k-1)|1`).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAs we process each index, we also update $dp[i] = \\max (dp[i], dp[i-1])$.\n\n# Complexity\n- Time complexity: $O(n)$\n\n- Space complexity: $O(n)$\n\n# Code\n```\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n if k == 1:\n return len(s)\n\n # manacher to find palindromes\n sp = "|" + "|".join(s) + "|"\n np = len(sp)\n radii = [0]*np\n center = radius = 0\n while center < np:\n # greedily increase the radius\n while center-radius-1 >= 0 and center+radius+1 < np and sp[center-radius-1] == sp[center+radius+1]:\n radius += 1\n radii[center] = radius\n\n # deal with sub-palindromes\n old_center = center\n old_radius = radius\n center += 1\n while center <= old_center+old_radius:\n lcenter = old_center-(center-old_center)\n max_radius = old_center+old_radius-center\n if radii[lcenter] < max_radius:\n # lcenter is a sub-palindrome of old_center\n # thus center is the same thing, just on the other side\n radii[center] = radii[lcenter]\n elif radii[lcenter] > max_radius:\n # lcenter expands beyond the palindrome at old_center\n # however, center is limited by max_radius\n # (or else old_radius would have been larger)\n radii[center] = max_radius\n else: # radii[lcenter] == max_radius:\n # the palindrome at center may or may not extend further\n # (depends if sp[lcenter-max_radius-1] == sp[center+max_radius+1])\n # continue the outer loop with center and radius\n radius = max_radius\n break\n center += 1\n radius = 0\n \n # maximum result for subproblem ending at index ip\n max_res = [0]*np\n for ip in range(1, np):\n max_res[ip] = max(max_res[ip], max_res[ip-1])\n if radii[ip] >= k:\n l = (ip-k-2)|1\n r = (ip+k-1)|1\n lmax = max_res[l] if l >= 0 else 0\n max_res[r] = max(max_res[r], lmax+1)\n\n return max_res[-1]\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Similar to Palindrome Partitioning II
|
similar-to-palindrome-partitioning-ii-by-59yy
|
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
|
sumitpal1234
|
NORMAL
|
2024-05-31T21:13:05.232466+00:00
|
2024-05-31T21:13:05.232492+00:00
| 1 | 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:\nint arr[2001][2001];\nvoid palin(string &s){\n int n= s.size();\n //length 1 palindrome\n for(int i=0;i<n;i++){\n arr[i][i]=1;\n }\n // length 2 palindrome\n for(int i=0;i<n-1;i++){\n if(s[i]==s[i+1])arr[i][i+1]=1;\n }\n //for length greater than 2\n for (int length = 3; length <= n; ++length) {\n for (int i = 0; i <= n - length; ++i) {\n int j = i + length - 1;\n arr[i][j] = (s[i] == s[j]) && arr[i + 1][j - 1];\n }\n }\n}\nbool check(string &s,int i,int j,int k){\n int len= i-j+1;\n if(len<k)return 0;\n while(j<=i){\n if(s[j]!=s[i])return 0;\n j++;\n i--;\n }\n return 1;\n}\nint solve(string &s,int i,int k,vector<int>&dp){\n\nif(i<0)return 0;\nif(dp[i]!=-1)return dp[i];\n int ans=0;\n for(int j=i;j>=0;j--){\n int len= i-j+1;\n if(len<k)continue;\n if(arr[j][i]){\n ans= max(ans,1 + solve(s,j-1,k,dp));\n }\n }\n ans= max(ans,solve(s,i-1,k,dp));\n return dp[i]=ans;\n}\n int maxPalindromes(string s, int k) {\n int n= s.size();\n vector<int>dp(n+1,-1);\n palin(s);\n return solve(s,n-1,k,dp);\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Python || Clean and Easy Dynamic Programming Solution
|
python-clean-and-easy-dynamic-programmin-a4hx
|
python\nfrom functools import cache\n\n\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n n = len(s)\n dp = self.palindrome
|
shivkj
|
NORMAL
|
2024-05-22T12:08:30.170106+00:00
|
2024-05-22T12:08:30.170135+00:00
| 11 | false |
```python\nfrom functools import cache\n\n\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n n = len(s)\n dp = self.palindrome_dp(s)\n\n @cache\n def max_palindromes(i: int) -> int:\n # finding idx such that s[i: idx + 1] is a palindrome\n idx = next(\n (j for j in range(i + k - 1, n) if dp[i][j]),\n n\n )\n\n if idx >= n:\n return 0\n else:\n return 1 + max(\n map(max_palindromes, range(idx + 1, n)),\n default=0,\n )\n\n return max(map(max_palindromes, range(n)))\n\n @staticmethod\n def palindrome_dp(s: str) -> list[list[bool]]:\n n = len(s)\n dp = [[False] * n for _ in range(n)]\n\n for end in range(n):\n for start in range(end + 1):\n dp[start][end] = s[start] == s[end] and (end - start < 2 or dp[start + 1][end - 1])\n\n return dp\n\n```
| 0 | 0 |
['Dynamic Programming', 'Memoization', 'Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
C++ || TOO EASY || CLEAN SHORT CODE || DP
|
c-too-easy-clean-short-code-dp-by-gaurav-w9kq
|
\n\n# Code\n\nclass Solution {\npublic:\n bool c(int i,int j,string &s)\n {\n while(i<j)\n if(s[i++]!=s[j--]) return 0;\n \n return 1;\
|
Gauravgeekp
|
NORMAL
|
2024-05-04T09:33:55.332669+00:00
|
2024-05-04T09:33:55.332692+00:00
| 2 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n bool c(int i,int j,string &s)\n {\n while(i<j)\n if(s[i++]!=s[j--]) return 0;\n \n return 1;\n }\n int t(int i,int n,string &s,vector<int> &dp,int k)\n {\n if(i>=n) return 0;\n if(dp[i]!=-1) return dp[i];\n\n int p=0,np=0;\n\n for(int j=i+k-1;j<n;j++)\n if(c(i,j,s)) {p=max(p,1+t(j+1,n,s,dp,k));break;}\n \n np=t(i+1,n,s,dp,k);\n\n return dp[i]=max(np,p);\n }\n int maxPalindromes(string s, int k) {\n int n=s.size();\n vector<int> dp(n+1,-1);\n return t(0,n,s,dp,k);\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
DP solution in Go
|
dp-solution-in-go-by-mesge-izfm
|
Intuition\n1. Find all the valid palindromes i.e. any palindromic sequence that is at least as long as k\n2. Expressed as intervals along a line we can greedily
|
mesge
|
NORMAL
|
2024-04-29T06:32:11.013205+00:00
|
2024-04-29T06:32:11.013244+00:00
| 9 | false |
# Intuition\n1. Find all the valid palindromes i.e. any palindromic sequence that is at least as long as k\n2. Expressed as intervals along a line we can greedily find those that do not overlap. Greedy algorithm means we optimise space along the line to allow room for more palindromes.\n3. Count them\n\n# Approach\nUsed a 2D matrix where x,y positions map to positions in the string where a palindrome starts and ends. Matrix lets us look at previously computed palindromes to assert palindrome when s[x] (start) and s[y] (end) chars are the same, and s[x-1] and s[y-1] are also the same, with special conditions for palindromes of length 1 (always palindromic) or 2 (only when both chars are the same).\n\n# Code\n```\nimport (\n\t"sort"\n)\n\ntype interval struct {\n\tstart, end int\n}\n\n// disjointIntervals is a greedy algorithm to find non-overlapping intervals along a line.\nfunc disjointIntervals(intervals []interval) []interval {\n\t// First we sort the intervals by their end positions\n\tsort.Slice(intervals, func(a, b int) bool { return intervals[a].end < intervals[b].end })\n\t// Now we can walk over the sorted intervals discarding those that overlap with the next.\n\t// If the start of the interval is less than the end of the last we can be sure they do not overlap.\n\t// By picking early we\'ve also optimised space along the line to find more non-overlapping intervals.\n\tvar res []interval\n\tlastEnd := -1\n\tfor _, i := range intervals {\n\t\tif i.start > lastEnd {\n\t\t\tres = append(res, i)\n\t\t\tlastEnd = i.end\n\t\t}\n\t}\n\treturn res\n}\n\n// validPalindromicIntervals returns intervals along string s that represent\n// start and end positions of a palindrome that is at least length k.\nfunc validPalindromicIntervals(s string, k int) []interval {\n\tn := len(s)\n\t// Store valid palindromes as intervals\n\tvar valid []interval\n\n\t// Make a square table to store start and end positions for all palindromes\n\ttable := make([][]bool, n)\n\tfor i := range table {\n\t\ttable[i] = make([]bool, n)\n\t}\n\n\t// Now walk over the string and find all palindromes for all possible lengths,\n // marking their positions and appending to the valid list if they\'re longer than k.\n\tfor pLength := 1; pLength <= n; pLength++ {\n\t\tfor y := 0; y <= n-pLength; y++ {\n\t\t\tx := y + pLength - 1\n\t\t\tif pLength == 1 {\n\t\t\t\ttable[y][x] = true\n\t\t\t} else if pLength == 2 {\n\t\t\t\ttable[y][x] = (s[y] == s[x])\n\t\t\t} else {\n\t\t\t\ttable[y][x] = (s[y] == s[x]) && table[y+1][x-1]\n\t\t\t}\n\n\t\t\tif table[y][x] && pLength >= k {\n\t\t\t\tvalid = append(valid, interval{y, x})\n\t\t\t}\n\t\t}\n\t}\n\treturn valid\n}\n\nfunc maxPalindromes(s string, k int) int {\n\t// We want to find the maximum number of non-overlapping palindromic\n\t// sequences in a string that are at least length k.\n\t//\n\t// It\'s in 3 parts\n\t// 1. We find all the palindromes of at least length k expressed as intervals along the sequences of chars in s\n\t// 2. We greedily find those that do not overlap\n\t// 3. We count the result\n\treturn len(\n\t\tdisjointIntervals(\n\t\t\tvalidPalindromicIntervals(s, k),\n\t\t),\n\t)\n}\n```
| 0 | 0 |
['Go']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Dynamic programming + Rolling Hash
|
dynamic-programming-rolling-hash-by-kaic-wpy5
|
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
|
kaicool9789
|
NORMAL
|
2024-03-15T09:00:04.711070+00:00
|
2024-03-15T09:00:04.711093+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 #define base 31\n #define ll long long\n const ll MOD = 1000000007LL;\n int maxPalindromes(string s, int k) {\n int n = s.size();\n string rs = s;\n reverse(rs.begin(), rs.end());\n s = \' \' + s;\n rs = \' \' + rs;\n vector<ll> hash1(n+1, 0);\n vector<ll> hash2(n+1, 0);\n vector<ll> p(n+1, 0);\n p[0] = 1LL;\n for (int i = 1 ; i <=n; i++) {\n p[i] = (p[i-1]*base)%MOD;\n hash1[i] = (hash1[i-1]*base + s[i] - \'0\' + 1LL)%MOD;\n hash2[i] = (hash2[i-1]*base + rs[i] - \'0\' + 1LL)%MOD;\n }\n function<ll(int,int)> gethash1 = [&](int l, int r) {\n return ((hash1[r] - hash1[l-1]*p[r-l+1]) %MOD + MOD)%MOD;\n };\n function<ll(int,int)> gethash2 = [&](int l, int r) {\n return ((hash2[r] - hash2[l-1]*p[r-l+1]) %MOD + MOD)%MOD;\n };\n\n int dp[n+2];\n memset(dp, -1,sizeof(dp));\n function<int(int)> find = [&] (int i) {\n if (i >n) return 0;\n int&res = dp[i];\n if(res!= -1) return res;\n int ans = 0;\n ans = max(ans, find(i+1));\n for (int j = i; j <= n; j++) {\n ll h1 = gethash1(i, j);\n ll h2 = gethash2(n-j+1, n-i+1);\n if (h1==h2 && (j-i+1) >= k) {\n ans = max(ans, 1 + find(j+1)); \n } \n } \n return res = ans;\n };\n return find(1);\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'Rolling Hash', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
java dp
|
java-dp-by-mot882000-okgg
|
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
|
mot882000
|
NORMAL
|
2024-02-12T12:04:53.032886+00:00
|
2024-02-12T12:04:53.032910+00:00
| 12 | 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 maxPalindromes(String s, int k) {\n\n // 1. \uBA3C\uC800 \uAC01 \uAD6C\uAC04\uC774 palindrome \uC778\uC9C0 \uAD6C\uD574\uC11C boolean isPalindrome[][] \uC5D0 \uC800\uC7A5\uD55C\uB2E4. \n \n // 2. dp[s.length()] \uB97C \uC120\uC5B8\uD55C\uB2E4. \n // dp[i] \uB294 index i\uAE4C\uC9C0 k\uAE38\uC774 \uC774\uC0C1 \uACB9\uCE58\uC9C0 \uC54A\uB294 \uD68C\uBB38\uC758 \uCD5C\uB300 \uC218 \n\n // i: 0 ~ s.legnth()-1 \uAE4C\uC9C0 \uC21C\uD68C\uD558\uBA74\uC11C\n // 1) j: i-k+1 ~ 0 \uAE4C\uC9C0 \uC21C\uD68C\uD55C\uB2E4. ( \uAE38\uC774 k \uBD80\uD130 \uC2DC\uC791 )\n // 2) isPalindrome[j][i] \uAC00 \uD68C\uBB38\uC774\uBA74 \n // dp[i] = Math.max(dp[i], 1+ dp[j-1] ) \u203B index j-1 \uAE4C\uC9C0 \uACB9\uCE58\uC9C0 \uC54A\uB294 \uD68C\uBB38\uC758 \uCD5C\uB300 \uAC1C\uC218 + 1 (\uD604\uC7AC \uD68C\uBB38)\n // isPalindrome[j][i] \uAC00 \uD68C\uBB38\uC774 \uC544\uB2C8\uBA74 \n // dp[i] = Math.max(dp[i], 0+ dp[j-1] ) \u203B index j-1 \uAE4C\uC9C0 \uACB9\uCE58\uC9C0 \uC54A\uB294 \uD68C\uBB38\uC758 \uCD5C\uB300 \uAC1C\uC218 + 0 (\uD604\uC7AC \uD68C\uBB38\uC774 \uC544\uB2C8\uB2E4.)\n \n // 3) 2)\uC5D0\uC11C dp[j-1]\uB9CC \uD655\uC778\uD560 \uC218 \uC788\uB3C4\uB85D dp[i] = Math.max(dp[i], dp[i-1]) \uD574\uC11C \uC624\uB978\uCABD\uC73C\uB85C max\uAC12\uC744 shifting \uD574\uC900\uB2E4. \n \n // 3. dp[dp.length-1] \uC5D0 \uCD5C\uB300 \uAC12\uC774 \uB4E4\uC5B4\uC788\uB2E4.\n\n boolean isPalindrome[][] = new boolean[s.length()][s.length()];\n\n for(int i = 0; i < isPalindrome.length; i++) isPalindrome[i][i] = true;\n\n for(int i = 1; i < s.length(); i++) {\n\n for(int j = 0; j < s.length(); j++) {\n if ( j+i == s.length()) break;\n if ( s.charAt(j) == s.charAt(j+i) && (isPalindrome[j+1][j+i-1] || i == 1) ) isPalindrome[j][j+i] = true;\n }\n }\n\n // for(int i = 0; i < isPalindrome.length; i++) {\n // for(int j = 0; j < isPalindrome[i].length; j++) {\n // if ( isPalindrome[i][j] ) System.out.println(i+" " + j + " " + isPalindrome[i][j] + " ");\n // }\n // }\n\n int dp[] = new int[s.length()];\n if ( isPalindrome[0][k-1] ) dp[k-1] = 1;\n \n for(int i = 0; i < dp.length; i++) {\n \n for(int j = i-k+1; j >= 0; j--) {\n if ( isPalindrome[j][i] ) {\n if ( j-1 >= 0 ) {\n dp[i] = Math.max(dp[i], 1+dp[j-1]);\n } else{\n dp[i] = Math.max(dp[i], 1);\n }\n } else{\n if ( j-1 >= 0 ) {\n dp[i] = Math.max(dp[i], 0+dp[j-1]);\n } \n }\n }\n\n if ( i-1 >= 0) dp[i] = Math.max(dp[i], dp[i-1]);\n }\n\n // for(int i = 0; i < dp.length; i++) System.out.print(dp[i] + " "); System.out.println();\n\n return dp[dp.length-1];\n }\n}\n```
| 0 | 0 |
['Dynamic Programming', 'Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
DP + greedy
|
dp-greedy-by-nuenuehao2-a593
|
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
|
nuenuehao2
|
NORMAL
|
2024-02-11T23:15:12.577117+00:00
|
2024-02-11T23:15:12.577136+00:00
| 7 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n n = len(s)\n # define a dp 2-D array, dp[i][j] = 0 means s[i:j+1] is not a palindrome string, dp[i][j] = -1 means s[i:j+1] is a palindrome string, dp[i][j] = 1 means s[i:j+1] is a palindrom string with length >= k.\n dp = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if s[i] == s[j] and (j - i <= 1 or dp[i + 1][j - 1] != 0):\n dp[i][j] = -1\n if j - i + 1 >= k:\n dp[i][j] = 1\n # greedy algorithm, find valid palindrom string from left to right, if i > end (meaning the current string is not overlapped with the previous string), then result += 1.\n result = 0\n end = -1\n for j in range(n):\n i = 0\n while i <= j:\n if dp[i][j] == 1 and i > end:\n result += 1\n end = j\n break\n else:\n i += 1\n return result\n \n\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Simple C++
|
simple-c-by-zerojude-v7uz
|
\n\n# Code\n\n#include <bits/stdc++.h>\nusing namespace std ;\n\n#define ar array< int , 2 >\n\nclass Solution {\n\n int go( vector< ar > &A )\n {\n
|
zerojude
|
NORMAL
|
2024-02-11T19:48:55.557555+00:00
|
2024-02-11T19:48:55.557584+00:00
| 5 | false |
\n\n# Code\n```\n#include <bits/stdc++.h>\nusing namespace std ;\n\n#define ar array< int , 2 >\n\nclass Solution {\n\n int go( vector< ar > &A )\n {\n if(A.size() <= 1 )\n return A.size() ;\n\n int N = A.size();\n sort( A.begin() , A.end() );\n\n vector<int>t(N,0);\n t[N-1] = 1 ;\n int res = 1 ;\n\n for( int i = N-2 ; i >= 0 ; i-- )\n {\n int a = A[i][0] ;\n int b = A[i][1] ;\n\n int j = lower_bound( A.begin() , A.end() , ar({b+1,-1}))-A.begin();\n\n t[i] = t[i+1];\n int c = 1 ;\n if( j < N )\n c += t[j];\n t[i] = max( t[i] , c );\n res = max( res , t[i] );\n }\n return res ;\n }\npublic:\n int maxPalindromes(string A , int k) {\n int N = A.size();\n int t[N][N];\n memset( t , 0 , sizeof t );\n\n vector< ar > B ;\n\n for( int i = 0 ; i < N ; i++ )\n {\n t[i][i] = 1 ;\n if(1>=k)\n B.push_back({i,i}); \n }\n for( int L = 2 ; L <= N ; L++ )\n for( int i = 0 ; i+L-1<N; i++ )\n {\n int j = i+L-1 ;\n if( A[i] == A[j] )\n t[i][j] = (L==2) || (t[i+1][j-1] );\n\n if(t[i][j] && L >= k)\n B.push_back({i,j});\n }\n\n return go( B );\n\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Java | Index+k | Index+k+1 | Odd -Even | Expansion | Greedy
|
java-indexk-indexk1-odd-even-expansion-g-wdkt
|
Intuition\n Describe your first thoughts on how to solve this problem. \nExpand from element till k and check for k length palindrome else check for k+i length
|
walichandpasha
|
NORMAL
|
2024-02-10T04:42:32.582058+00:00
|
2024-02-10T04:42:32.582081+00:00
| 6 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExpand from element till k and check for k length palindrome else check for k+i length palindrome\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will go to each element and check for both even and odd length of size, first even and then odd, if we found that from axis there is a palindrome then we take new axis which is axis + orbit or index + k in case of even and index+k+1 in case of odd else we shift to next index.\n\nIntrestingly if you check first odd and then even few test cases will fail as it misses few cases due to else if condition.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*k)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\n public int maxPalindromes(String s, int orbit) {\n int axis = 0, ans = 0;\n while(axis < s.length()){\n if(axis+orbit-1 < s.length() && isPalindrome(s, axis, axis+orbit-1)){ //even\n axis += orbit;\n ans++;\n }else if(axis + orbit < s.length() && isPalindrome(s, axis, axis+orbit)){ //odd\n axis += orbit+1;\n ans++;\n }else{\n axis++;\n }\n }\n return ans;\n }\n\n public boolean isPalindrome(String s, int begin, int end){\n while(begin < end){\n if(s.charAt(begin++) != s.charAt(end--)){\n return false;\n }\n }\n return true;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Java | Index+k | Index+k+1 | Odd -Even | Expansion | Greedy
|
java-indexk-indexk1-odd-even-expansion-g-jen0
|
Intuition\n Describe your first thoughts on how to solve this problem. \nExpand from element till k and check for k length palindrome else check for k+i length
|
walichandpasha
|
NORMAL
|
2024-02-10T04:42:31.216442+00:00
|
2024-02-10T04:42:31.216479+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExpand from element till k and check for k length palindrome else check for k+i length palindrome\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will go to each element and check for both even and odd length of size, first even and then odd, if we found that from axis there is a palindrome then we take new axis which is axis + orbit or index + k in case of even and index+k+1 in case of odd else we shift to next index.\n\nIntrestingly if you check first odd and then even few test cases will fail as it misses few cases due to else if condition.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*k)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\n public int maxPalindromes(String s, int orbit) {\n int axis = 0, ans = 0;\n while(axis < s.length()){\n if(axis+orbit-1 < s.length() && isPalindrome(s, axis, axis+orbit-1)){ //even\n axis += orbit;\n ans++;\n }else if(axis + orbit < s.length() && isPalindrome(s, axis, axis+orbit)){ //odd\n axis += orbit+1;\n ans++;\n }else{\n axis++;\n }\n }\n return ans;\n }\n\n public boolean isPalindrome(String s, int begin, int end){\n while(begin < end){\n if(s.charAt(begin++) != s.charAt(end--)){\n return false;\n }\n }\n return true;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
DP+LIS
|
dplis-by-trunkunala-3ba7
|
Intuition\nThe idea is to record index pairs for all palindromic substrings within the string s, and then perform a Longest Increasing Sequence on it.\n\n# Appr
|
trunkunala
|
NORMAL
|
2024-02-06T07:32:47.413376+00:00
|
2024-02-06T07:32:47.413400+00:00
| 21 | false |
# Intuition\nThe idea is to record index pairs for all palindromic substrings within the string s, and then perform a Longest Increasing Sequence on it.\n\n# Approach\n*Step 1:* Create the boolean array to record all left-right index pairs of palindrome.\n*Step 2:* Record these pairs, and perform an LIS \n\n\n# Code\n```\nclass Solution {\n Boolean[][] memo;\n public int maxPalindromes(String s, int k) {\n this.memo = new Boolean[s.length()+1][s.length()+1];\n if(k==1) return s.length();\n if(s.length()==1) return 1;\n if(dfs(s, 0, s.length()-1)) return s.length()%k==0?s.length()/k:1; \n \n dfs(s,0,s.length()-1);\n\n List<int[]> list = new ArrayList(); \n \n for(int i=0; i<memo.length; i++){\n for(int j=0; j<memo[0].length; j++){\n \n if(memo[i][j]!=null && memo[i][j] && j-i+1>=k){\n list.add(new int[]{i, j});\n }\n\n }\n }\n\n if(list.size()==1) return 1;\n // return list.size();\n return getNonOverlap(list);\n \n\n }\n\n boolean dfs(String s, int l, int r){\n\n if(l>=r) return memo[l][r]=true;\n if(memo[l][r]!=null) return memo[l][r];\n dfs(s,l+1,r);\n dfs(s, l, r-1);\n if(s.charAt(l)==s.charAt(r)) return memo[l][r] = dfs(s,l+1,r-1);\n else return memo[l][r] = false; \n\n }\n\n int getNonOverlap(List<int[]> list){\n\n int[] memo2 = new int[list.size()];\n\n Arrays.fill(memo2, -1);\n\n dp(list, memo2,0);\n\n int res = 0;\n\n for(int i=0 ;i<memo2.length; i++){\n res = Math.max(res, memo2[i]);\n }\n\n return res;\n\n }\n\n int dp(List<int[]> list, int[] memo2, int index){\n \n if(index == list.size()-1) return 1;\n if(index==list.size()) return 0;\n if(memo2[index]!=-1) return memo2[index];\n int sub = 0;\n for(int i=index+1; i<list.size(); i++){\n\n if(list.get(index)[1]<list.get(i)[0]){\n sub = Math.max(dp(list, memo2, i),sub);\n }\n\n }\n\n dp(list,memo2, index+1);\n\n return memo2[index] = sub+1;\n\n }\n\n\n}\n```
| 0 | 0 |
['Dynamic Programming', 'Memoization', 'Java']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
💡💡 Center expansion with non overlapping intervals solution in python
|
center-expansion-with-non-overlapping-in-8d78
|
Intuition\n Describe your first thoughts on how to solve this problem. \nFind out even and odd lengted palindromes using center expansion and include them in th
|
shrishtikarkera
|
NORMAL
|
2024-01-23T21:44:40.634959+00:00
|
2024-01-23T21:44:40.634987+00:00
| 5 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind out even and odd lengted palindromes using center expansion and include them in the intervals list if the palindromic length is >= k. Now get the number of non overlapping intervals and return those. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn the palindrome function that returns the left and right window indices of the palindrome, we return the left and right index if the window size >= k because the smaller the window, the max palindromes we can return - "as we\'re supposed to maximize that number"\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def maxPalindromes(self, s: str, k: int) -> int:\n \n\n <!-- finding palindromes using center expansion -->\n def palindrome(i, j):\n if s[i] != s[j]:\n return (i+1, j-1)\n elif j-i+1 >= k:\n return (i, j)\n else:\n if i-1 >=0 and j+1 < len(s):\n return palindrome(i-1, j+1)\n else:\n return (i, j)\n \n intervals = []\n\n<!-- for odd lengthed palindromes: -->\n for i in range(len(s)):\n left, right = palindrome(i, i)\n if left > i:\n left = right = i\n if i == 6:\n print("i = 6", left, right)\n if right-left+1 >= k:\n intervals.append([left, right])\n\n <!-- for even lengthed palindromes -->\n for i in range(len(s)-1):\n if s[i] != s[i+1]:\n continue\n left, right = palindrome(i, i+1)\n if left > i:\n left = i\n right = i+1\n if right-left+1 >= k:\n intervals.append([left, right])\n\n<!-- Get the number of non overlapping intervals -->\n if not intervals:\n return 0\n intervals.sort()\n res = 0\n prevEnd = intervals[0][1]\n for start, end in intervals[1:]:\n if start > prevEnd:\n prevEnd = end\n else:\n res += 1\n prevEnd = min(prevEnd, end)\n return len(intervals) - res\n\n```
| 0 | 0 |
['Python3']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
O(n^2) Sol with easy loops without DP and extra space
|
on2-sol-with-easy-loops-without-dp-and-e-mwhm
|
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Check pal at each char\n2. Make sure to check two ways Expanding wodnow (i, i) and
|
Bulls_eye1
|
NORMAL
|
2024-01-22T21:57:53.723335+00:00
|
2024-01-22T21:57:53.723356+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Check pal at each char\n2. Make sure to check two ways Expanding wodnow (i, i) and (i, i + 1)\n3. If found adjust your out loop next ith iteration\n4. greedy to look for minimum pal \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int sLen = 0;\n int retCount = 0;\n int celingStart = 0; // this is required to prevent overlapping\n\npublic:\n\n // expanding window pal check logic\n bool\n isPal(string &s, int &start, int &end, int k) {\n while ((start >= celingStart && end < sLen) && s[start] == s[end]) {\n if (end - start + 1 >= k) {\n string sub = s.substr(start, end - start +1);\n //cout<<"pal: "<<sub<<endl;\n return true;\n }\n --start;\n ++end;\n }\n\n return false;\n }\n int maxPalindromes(string s, int k) {\n sLen = s.length();\n \n if (!sLen || k > sLen) {\n return 0;\n }\n\n for (int i = 0; i < s.length();) {\n int start = i;\n int end = i;\n if (isPal(s, start, end, k)) {\n i = end + 1;\n celingStart = end + 1;\n ++retCount;\n continue;\n }\n\n start = i;\n end = i + 1;\n\n if (isPal(s, start, end, k)) {\n i = end + 1;\n celingStart = end + 1;\n ++retCount;\n continue;\n }\n\n ++i;\n }\n\n\n return retCount;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Front partition
|
front-partition-by-chakit_bhandari-zekh
|
Intuition\nAt each index i we have a choice whether to at each particular indices ending at j=i+k-1...n-1 or start at a new position i+1. Take the maximum out o
|
Chakit_Bhandari
|
NORMAL
|
2023-12-07T19:22:42.897607+00:00
|
2023-12-07T19:22:42.897634+00:00
| 4 | false |
# Intuition\nAt each index $$i$$ we have a choice whether to at each particular indices ending at $$j=i+k-1...n-1$$ or start at a new position $$i+1$$. Take the maximum out of these choices and return the ans.\n\n# Complexity\n- Time complexity: $$O(n*n)$$\n- Space complexity: $$O(n*n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<bool>>ispal;\n vector<int>dp;\n int f(int i,string &s,int k){\n // base case\n if(i>=s.size()) return 0;\n if(dp[i]!=-1) return dp[i];\n int ans = f(i+1,s,k);\n for(int j=i+k-1;j<s.size();++j){\n if(ispal[i][j]) ans = max(ans,1+f(j+1,s,k));\n }\n return dp[i] = ans;\n }\n\n int maxPalindromes(string s, int k) {\n int n=s.size();\n ispal = vector<vector<bool>>(n,vector<bool>(n));\n for(int i=n-1;i>=0;i--){\n for(int j=0;j<n;++j){\n if(i>j) ispal[i][j] = true;\n else if(i==j) ispal[i][j] = true;\n else ispal[i][j] = s[i]==s[j] and ispal[i+1][j-1];\n }\n }\n dp = vector<int>(n,-1);\n return f(0,s,k);\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
0/1 Knapsack pattern
|
01-knapsack-pattern-by-chakit_bhandari-58dg
|
Intuition\nAt each index j we have three choices.\nEither we can end a substring at this position if s[i..j] is a palindrome\nOR\nWe can a end a substring at an
|
Chakit_Bhandari
|
NORMAL
|
2023-12-07T19:20:25.149960+00:00
|
2023-12-07T19:20:25.149996+00:00
| 1 | false |
# Intuition\nAt each index $$j$$ we have three choices.\nEither we can end a substring at this position if $$s[i..j]$$ is a palindrome\nOR\nWe can a end a substring at an index greater than $$j$$ in which case length still remains atleast $$k$$\nOR\nWe can start a new string at index $$i+1$$ and end at $$i+k$$.\n\nTake the maximum out of all these choices and return the ans to the current sub-problem.\n\n# Complexity\n- Time complexity: $$O(n*n)$$\n- Space complexity:c$$O(n*n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<bool>>ispal;\n vector<vector<int>>dp;\n int f(int i,int j,string &s,int k){\n // base case\n if(j>=s.size()) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int ans = max(f(i+1,i+k,s,k),f(i,j+1,s,k));\n if(ispal[i][j]) ans = max(ans,1+f(j+1,j+k,s,k));\n return dp[i][j] = ans;\n }\n\n int maxPalindromes(string s, int k) {\n int n=s.size();\n ispal = vector<vector<bool>>(n,vector<bool>(n));\n for(int i=n-1;i>=0;i--){\n for(int j=0;j<n;++j){\n if(i>j) ispal[i][j] = true;\n else if(i==j) ispal[i][j] = true;\n else ispal[i][j] = s[i]==s[j] and ispal[i+1][j-1];\n }\n }\n dp = vector<vector<int>>(n,vector<int>(n,-1));\n return f(0,k-1,s,k);\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximum-number-of-non-overlapping-palindrome-substrings
|
Koltin | Approach Explained | Beats 100%
|
koltin-approach-explained-beats-100-by-m-27tt
|
Intuition\nThis problem is a combination of Non-overlapping intervals and Number of Palindromic Substrings\nhttps://leetcode.com/problems/non-overlapping-interv
|
Mahoraga_JJK
|
NORMAL
|
2023-12-05T21:13:23.474835+00:00
|
2023-12-05T21:13:23.474889+00:00
| 3 | false |
# Intuition\nThis problem is a combination of Non-overlapping intervals and Number of Palindromic Substrings\nhttps://leetcode.com/problems/non-overlapping-intervals/\nhttps://leetcode.com/problems/palindromic-substrings/\n\n# Approach\nStart by finding all palindromic substrings with length >= k and update result according to make sure the current interval is the optimal and we cover maximum number of intervals. Using last to store the end index of substring if last is less than the current substring start we know we have a new interval to add and its end index is the new last or else if start is lower than last and end is also lower than last then we can replace this current substring with the last one to have more substring in our result. \n\n# Complexity\n- Time complexity:\n $$O(nk)$$\n\n- Space complexity:\n $$Constant$$\n\n# Code\n```\nclass Solution {\n fun maxPalindromes(s: String, k: Int): Int {\n val n: Int = s.length\n var last: Int = Int.MIN_VALUE\n var ans = 0\n var place = -1\n while(++place<2*n) {\n var left = place/2\n var right = left + place%2\n while(left>=0 && right<n && s[left]==s[right]){\n if (right+1-left>=k) {\n if (left>=last) {\n last=right+1\n ans++\n }\n else if (right+1<last) last = right+1\n break\n } \n left--\n right++\n }\n }\n return ans \n }\n}\n\n//class Solution {\n// fun maxPalindromes(s: String, k: Int): Int {\n// val n: Int = s.length\n// var last: Int = Int.MIN_VALUE\n// var ans = 0\n// val intervals: MutableList<List<Int>> = ArrayList()\n// var place = -1\n// while(++place<2*n) {\n// var left = place/2\n// var right = left + place%2\n// while(left>=0 && right<n && s[left]==s[right]){\n// if (right+1-left>=k) {\n// intervals.add(listOf(left,right+1))\n// \n// break\n// } \n// left--\n// right++\n// }\n// }\n// intervals.forEach{\n// if (it.get(0)>=last) {\n// last = it.get(1)\n// ans++\n// }\n// else if (it.get(1)<last) \n// last = it.get(1)\n// }\n// return ans \n// }\n//}\n\n```
| 0 | 0 |
['Kotlin']
| 0 |
count-substrings-with-k-frequency-characters-i
|
[Java/C++/Python] Sliding Window, O(n)
|
javacpython-sliding-window-on-by-lee215-91da
|
Intuition\n(n + 1) * n // 2 substrings in total.\nFind the number of substrings,\neach char appears at most k - 1 times.\n\n\n# Intuition2\nNo problem II in th
|
lee215
|
NORMAL
|
2024-10-20T04:12:51.736151+00:00
|
2024-10-20T04:27:49.706265+00:00
| 3,302 | false |
# **Intuition**\n`(n + 1) * n // 2` substrings in total.\nFind the number of substrings,\neach char appears at most `k - 1` times.\n<br>\n\n# **Intuition2**\nNo problem **II** in the contest?\nUpvote this solution,\nand submit it directly in next contest!\n<br>\n\n# **Explanation**\nSolve with sliding window:\n\nEach iteration,\nappend `s[j]` on the right,\nwhile `count[s[j]] >= k`,\nmove the left pointer until it\'s not.\ncount the substring ending with `s[j]` in the window.\nremove them from result.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n```Java [Java]\n public int numberOfSubstrings(String s, int k) {\n int n = s.length(), res = (n + 1) * n / 2;\n int[] count = new int[26];\n for (int i = 0, j = 0; j < n; j++) {\n char c = s.charAt(j);\n count[c - \'a\']++;\n while (count[c - \'a\'] >= k) {\n char leftChar = s.charAt(i);\n count[leftChar - \'a\']--;\n i++;\n }\n res -= j - i + 1;\n }\n return res;\n }\n```\n\n```C++ [C++]\n int numberOfSubstrings(string s, int k) {\n int n = s.length(), res = (n + 1) * n / 2;\n unordered_map<char, int> count;\n for (int i = 0, j = 0; j < n; j++) {\n count[s[j]]++;\n while (count[s[j]] >= k)\n --count[s[i++]];\n res -= j - i + 1;\n }\n return res;\n }\n```\n\n```py [Python3]\n def numberOfSubstrings(self, s: str, k: int) -> int:\n n = len(s)\n res = (n + 1) * n // 2\n count = Counter()\n i = 0\n for j in range(n):\n count[s[j]] += 1\n while count[s[j]] >= k:\n count[s[i]] -= 1\n i += 1\n res -= j - i + 1\n return res\n```\n
| 54 | 4 |
['C', 'Python', 'Java']
| 8 |
count-substrings-with-k-frequency-characters-i
|
Easiest Solution 🔥✅ | Sliding Window | BEATS 94.94%
|
easiest-solution-sliding-window-beats-94-auol
|
Intuition\nWe need to count substrings where at least one character appears exactly k times. A sliding window approach helps us track character frequencies and
|
1AFN19tfV2
|
NORMAL
|
2024-10-20T04:01:54.384958+00:00
|
2024-10-23T16:27:34.579349+00:00
| 2,883 | false |
# Intuition\nWe need to count substrings where at least one character appears exactly `k` times. A sliding window approach helps us track character frequencies and adjust the window to find valid substrings efficiently.\n\n# Approach\n1. Use a sliding window with a pointer `l` and a frequency map `d` to track characters in the window.\n2. For each character, update its frequency in `d`.\n3. If any character\'s frequency reaches `k`, shrink the window by incrementing `l`.\n4. Add the number of valid starting positions (`l`) to the result for each window.\n5. Return the total count of valid substrings.\n\n# Complexity\n- Time complexity: $$O(n)$$, where n is the length of the string.\n\n- Space complexity: $$O(1)$$, since the maximum number of items we store in our hashmap is 26 (every letter).\n\n# Code\n```python3 []\nclass Solution:\n def numberOfSubstrings(self, s: str, k: int) -> int:\n ans = 0\n l = 0\n d = {}\n for c in s:\n d[c] = d.get(c, 0) + 1\n while d[c] == k:\n d[s[l]] -= 1\n l += 1\n ans += l\n return ans\n```\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int ans = 0;\n int l = 0;\n unordered_map<char, int> d;\n \n for (char c : s) {\n d[c]++;\n while (d[c] == k) {\n d[s[l]]--;\n l++;\n }\n ans += l;\n }\n \n return ans;\n }\n};\n```\n```java []\nimport java.util.HashMap;\n\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int ans = 0;\n int l = 0;\n HashMap<Character, Integer> d = new HashMap<>();\n \n for (char c : s.toCharArray()) {\n d.put(c, d.getOrDefault(c, 0) + 1);\n \n while (d.get(c) == k) {\n d.put(s.charAt(l), d.get(s.charAt(l)) - 1);\n l++;\n }\n \n ans += l;\n }\n\n return ans;\n }\n}\n```\n\n
| 26 | 0 |
['Sliding Window', 'C++', 'Java', 'Python3']
| 5 |
count-substrings-with-k-frequency-characters-i
|
Simple Java Solution ✅
|
simple-java-solution-by-shubhamyadav3210-xvzu
|
Approach\n- I used a nested loop to examine each substring. \n- For each starting point, I tracked character frequencies and checked if any character\'s frequen
|
shubhamyadav32100
|
NORMAL
|
2024-10-20T04:02:56.189189+00:00
|
2024-10-20T10:46:15.612814+00:00
| 1,124 | false |
# Approach\n- I used a nested loop to examine each substring. \n- For each starting point, I tracked character frequencies and checked if any character\'s frequency reached `k`. \n- If it did, I counted all remaining substrings from that point onward.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(1)$$ (fixed size array for character frequency)\n\n# Code\n```java\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int n = s.length();\n int count = 0;\n\n for (int left = 0; left < n; left++) {\n int[] freq = new int[26];\n int maxFreq = 0;\n\n for (int right = left; right < n; right++) {\n freq[s.charAt(right) - \'a\']++;\n maxFreq = Math.max(maxFreq, freq[s.charAt(right) - \'a\']);\n\n if (maxFreq >= k) {\n count += n - right;\n break;\n }\n }\n }\n return count;\n }\n}\n```\n\n## Updated code\n\n```\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int n = s.length();\n int count = 0;\n\n for (int left = 0; left < n; left++) {\n int[] freq = new int[26];\n\n for (int right = left; right < n; right++) {\n freq[s.charAt(right) - \'a\']++;\n\n if (freq[s.charAt(right) - \'a\'] >= k) {\n count += n - right;\n break;\n }\n }\n }\n return count;\n }\n}\n```\n\n# Upvote if you found this helpful! \uD83D\uDE0A
| 23 | 0 |
['Java']
| 1 |
count-substrings-with-k-frequency-characters-i
|
🌟 Beats 100.00% 👏 || Count Sub strings With K-Frequency Characters I
|
beats-10000-count-sub-strings-with-k-fre-h2l4
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem revolves around counting substrings of a string s where a specific charact
|
srinivas_bodduru
|
NORMAL
|
2024-10-20T08:22:09.051966+00:00
|
2024-10-20T08:22:09.051996+00:00
| 1,006 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem revolves around counting substrings of a string s where a specific character appears exactly k times. \n\nIterate through the string: For every starting point i in the string, consider every possible substring starting at i and ending at j (i.e., s[i:j]).\n\nTrack character frequency: Use an array freqArr of size 26 (for lowercase English letters) to keep track of how many times each character appears in the substring s[i:j].\n\nCondition to stop: For each character at index j, increment its frequency in freqArr. If at any point, the frequency of the current character matches k, then every substring that starts at i and ends from j to the end of the string will meet the condition.\n\nCounting valid substrings: Once a valid substring is found (i.e., a character appears exactly k times), you can add all substrings starting at i and ending from j to the end of the string to the answer, because adding more characters beyond j will still have that character appear at least k times.\n\nEfficiency consideration: Even though this is a brute-force approach, the inner loop breaks as soon as the condition is met to avoid unnecessary further checks.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s walk through an example where s = "abcabc" and k = 2.\n\nIteration with i = 0:\n\nStart with the substring beginning at index 0.\nInitialize freqArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].\nInner Loop with j = 0:\n\nThe character is \'a\'. Increment freqArr[0].\nNow freqArr = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].\n\'a\' has not appeared k=2 times yet, so continue to the next j.\nInner Loop with j = 1:\n\nThe character is \'b\'. Increment freqArr[1].\nNow freqArr = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].\nNeither \'a\' nor \'b\' has appeared k=2 times yet, so continue to the next j.\nInner Loop with j = 2:\n\nThe character is \'c\'. Increment freqArr[2].\nNow freqArr = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].\nStill no character appears k=2 times yet. Continue to j = 3.\nInner Loop with j = 3:\n\nThe character is \'a\'. Increment freqArr[0].\nNow freqArr = [2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].\nNow \'a\' appears exactly k=2 times.\nAdd s.length() - j = 6 - 3 = 3 to ans, and break the inner loop.\nThe total count is now ans = 3.\n\nWe continue this process for i = 1, i = 2, and so on, updating freqArr for each new starting point.\n# Complexity\n- Time complexity:O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```javascript []\nvar numberOfSubstrings = function (s, k) {\n let ans = 0;\n\n for (let i = 0; i < s.length; i++) {\n let freqArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n for (let j = i; j < s.length; j++) {\n freqArr[s.charCodeAt(j) - 97]++;\n \n if (freqArr[s.charCodeAt(j) - 97] == k) {\n ans += s.length - j\n break\n }\n }\n }\n\n return ans;\n};\n```\n```python []\ndef numberOfSubstrings(s, k):\n ans = 0\n\n for i in range(len(s)):\n freqArr = [0] * 26\n\n for j in range(i, len(s)):\n freqArr[ord(s[j]) - ord(\'a\')] += 1\n \n if freqArr[ord(s[j]) - ord(\'a\')] == k:\n ans += len(s) - j\n break\n \n return ans\n\n```\n```java []\npublic class Solution {\n public int numberOfSubstrings(String s, int k) {\n int ans = 0;\n\n for (int i = 0; i < s.length(); i++) {\n int[] freqArr = new int[26];\n\n for (int j = i; j < s.length(); j++) {\n freqArr[s.charAt(j) - \'a\']++;\n\n if (freqArr[s.charAt(j) - \'a\'] == k) {\n ans += s.length() - j;\n break;\n }\n }\n }\n\n return ans;\n }\n}\n\n```\n```c []\n#include <stdio.h>\n#include <string.h>\n\nint numberOfSubstrings(char* s, int k) {\n int ans = 0;\n int n = strlen(s);\n\n for (int i = 0; i < n; i++) {\n int freqArr[26] = {0};\n\n for (int j = i; j < n; j++) {\n freqArr[s[j] - \'a\']++;\n\n if (freqArr[s[j] - \'a\'] == k) {\n ans += n - j;\n break;\n }\n }\n }\n\n return ans;\n}\n```\n```c++ []\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint numberOfSubstrings(string s, int k) {\n int ans = 0;\n\n for (int i = 0; i < s.length(); i++) {\n vector<int> freqArr(26, 0);\n\n for (int j = i; j < s.length(); j++) {\n freqArr[s[j] - \'a\']++;\n\n if (freqArr[s[j] - \'a\'] == k) {\n ans += s.length() - j;\n break;\n }\n }\n }\n\n return ans;\n}\n```\n
| 14 | 0 |
['Recursion', 'C', 'Simulation', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript']
| 3 |
count-substrings-with-k-frequency-characters-i
|
Simple Brute Force
|
simple-brute-force-by-_sxrthakk-zmwn
|
Intuition\n#### The key idea is to explore all possible substrings of s and, for each substring, check if any character appears k or more times. This can be don
|
_sxrthakk
|
NORMAL
|
2024-10-20T04:02:00.502780+00:00
|
2024-10-20T04:02:00.502809+00:00
| 818 | false |
# Intuition\n#### The key idea is to explore all possible substrings of s and, for each substring, check if any character appears k or more times. This can be done by generating all substrings and counting the frequency of each character for each substring. If at least one character satisfies the condition of appearing k or more times, we increase the count.\n\n#### However, this approach is not optimal since generating all substrings leads to a time complexity of O(n^2), and then checking each substring to see if it has a character appearing k times adds further complexity. Still, this brute-force solution gives a correct answer.\n\n# Approach\n#### 1. **Generate All Possible Substrings :**\n- A substring is defined as any contiguous part of the string s. To generate all substrings, we need to iterate over all possible starting points (i) and all possible ending points (j) for each starting point.\n- This can be done using two loops:\n -- The outer loop fixes the starting point i (runs from 0 to n-1).\n -- The inner loop fixes the ending point j (runs from i to n-1).\n\n#### 2. **Use a Frequency Map to Track Character Counts :**\n- For each substring starting at i and ending at j, we need to check how many times each character appears in that substring.\n- We use an unordered_map<char, int> (hash map) to store the frequency of each character in the current substring.\n- For every new character added to the substring (as j increases), we update the frequency in the map.\n#### 3. **Check if Any Character Appears k Times :**\n- After updating the frequency map for the substring ending at j, we need to check whether any character in the current substring has appeared at least k times.\n- This is done by iterating over the map and checking if any character\'s frequency is greater than or equal to k. If this condition is satisfied, we set a flag (f = true) and break out of the loop.\n#### 4. **Count Valid Substrings :**\n- If the flag f is set to true (i.e., at least one character in the current substring appears k times), we increment the count c for valid substrings.\n\n#### 5. **Return the Total Count :**\n- Once both loops finish, the final count c represents the total number of substrings where at least one character appears at least k times. This count is returned as the result.\n\n# Example Walkthrough\n### Let\u2019s take an example with s = "abbc" and k = 2:\n\n1. **Outer Loop (i = 0) :**\n- Starting point i = 0, substrings generated: "a", "ab", "abb", "abbc"\n- Map updates:\n-- For "a": {a: 1} \u2192 No character appears k = 2 times.\n-- For "ab": {a: 1, b: 1} \u2192 No character appears k = 2 times.\n-- For "abb": {a: 1, b: 2} \u2192 b appears 2 times, so this substring is valid.\n-- For "abbc": {a: 1, b: 2, c: 1} \u2192 b appears 2 times, so this substring is valid.\n-- Valid substrings so far: "abb", "abbc"\n\n2. **Outer Loop (i = 1) :**\n- Starting point i = 1, substrings generated: "b", "bb", "bbc"\n- Map updates:\n-- For "b": {b: 1} \u2192 No character appears k = 2 times.\n-- For "bb": {b: 2} \u2192 b appears 2 times, so this substring is valid.\n-- For "bbc": {b: 2, c: 1} \u2192 b appears 2 times, so this substring is valid.\n-- Valid substrings so far: "bb", "bbc"\n\n3. **Outer Loop (i = 2) :**\n\n- Starting point i = 2, substrings generated: "b", "bc"\n- Map updates:\n-- For "b": {b: 1} \u2192 No character appears k = 2 times.\n-- For "bc": {b: 1, c: 1} \u2192 No character appears k = 2 times.\n- No valid substrings found for i = 2.\n\n4. **Outer Loop (i = 3) :**\n\n- Starting point i = 3, substrings generated: "c"\n- Map updates:\n-- For "c": {c: 1} \u2192 No character appears k = 2 times.\n-- No valid substrings found for i = 3.\n\n5. **Final Count :**\n- The valid substrings found are: "abb", "abbc", "bb", and "bbc". Hence, the total count c is 4.\n\n# Code\n```cpp []\nint numberOfSubstrings(string s, int k) {\n int c=0;\n\n for(int i=0;i<s.size();i++){\n unordered_map<char, int> m;\n for(int j=i;j<s.size();j++){\n m[s[j]]++; \n \n bool f=false;\n for (auto x : m){\n if(x.second>=k){\n f=true;\n break;\n }\n }\n \n if(f) c++;\n }\n }\n\n return c;\n}\n```\n\n``` Java []\npublic int numberOfSubstrings(String s, int k) {\n int c = 0;\n \n for (int i = 0; i < s.length(); i++) {\n HashMap<Character, Integer> charCount = new HashMap<>();\n \n for (int j = i; j < s.length(); j++) {\n charCount.put(s.charAt(j), charCount.getOrDefault(s.charAt(j), 0) + 1);\n \n boolean valid = false;\n for (int freq : charCount.values()) {\n if (freq >= k) {\n valid = true;\n break;\n }\n }\n \n if (valid) {\n c++;\n }\n }\n }\n \n return c;\n}\n```\n\n``` Python []\ndef numberOfSubstrings(s: str, k: int) -> int:\n c = 0\n for i in range(len(s)):\n char_count = {}\n for j in range(i, len(s)):\n char_count[s[j]] = char_count.get(s[j], 0) + 1\n valid = False\n for freq in char_count.values():\n if freq >= k:\n valid = True\n break\n if valid:\n c += 1\n return c\n```\n\n
| 10 | 0 |
['Python', 'C++', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
O(n)
|
on-by-votrubac-e5c6
|
We expand the sliding window, maintaining the count of each character in cnt.\n\nWhen we cnt[ch] becomes k, we increase the number of "k+" characters ch_k.\n\nW
|
votrubac
|
NORMAL
|
2024-10-20T06:48:35.888883+00:00
|
2024-10-20T06:54:46.561812+00:00
| 530 | false |
We expand the sliding window, maintaining the count of each character in `cnt`.\n\nWhen we `cnt[ch]` becomes `k`, we increase the number of "k+" characters `ch_k`.\n\nWhen `ch_k` is positive, we find `len(s) - i` substrings.\n\nWe then shrink our window until `ch_k` becomes zero.\n\n**C++**\n```cpp\nint numberOfSubstrings(string s, int k) {\n int cnt[26] = {}, ch_k = 0, res = 0, j = 0;\n for (int i = 0; i < s.size(); ++i) {\n ch_k += ++cnt[s[i] - \'a\'] == k;\n for (; ch_k; ++j) {\n res += s.size() - i;\n ch_k -= cnt[s[j] - \'a\']-- == k;\n }\n }\n return res;\n}\n```
| 9 | 0 |
['C']
| 1 |
count-substrings-with-k-frequency-characters-i
|
Easy Explained || O(n) || Two Pointer Approach
|
easy-explained-on-two-pointer-approach-b-x1u3
|
Approach:\n\nWe can solve this problem using the sliding window (or two-pointer) technique along with character frequency counting. The main idea is to maintain
|
nikhiljangra264
|
NORMAL
|
2024-10-20T04:22:38.711228+00:00
|
2024-10-20T05:03:47.479312+00:00
| 514 | false |
# Approach:\n\nWe can solve this problem using the **sliding window** (or two-pointer) technique along with character frequency counting. The main idea is to maintain a window `[i, j]` such that `s[j]` in the window appears `k` times.\n\n# Steps:\n\n1. **Sliding Window Setup:**\n - Use two pointers `i` and `j` to represent the window.\n - We use an array `ccount[26]` to track the frequency of each character in the window.\n\n2. **Main Logic:**\n - increment `s[j]` frequency in `ccount`.\n - If the frequency of `s[j]` is greater than or equal to `k`, this means we have found a valid substring from `i` to `j`. \n - Add the count of all possible substrings starting from `i` and ending at `j` to `n-1` (since any further extension of this substring `i...j` will also be valid). The number of such substrings is `n - j`.\n - increase `i` pointer till `ccount[s[j]] >= k`.\n\n# Complexity\n- Time complexity:\n\nWe are traversing the array one time via `i and j` pointers. So the time complexity is $$O(n)$$.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nConstant extra space `int[26]` is used so the space complexity is $$O(1)$$.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int ccount[26] = {0};\n int i=0,j=0;\n int count = 0, n = s.size();\n\n while(j<n) {\n int c=s[j]-\'a\';\n ccount[c]++;\n while(ccount[c]>=k) {\n count += n-j;\n ccount[s[i]-\'a\']--;\n i++;\n }\n j++;\n }\n return count;\n }\n};\n```\n\n# Please Upvote
| 7 | 0 |
['C++']
| 1 |
count-substrings-with-k-frequency-characters-i
|
⚠️ INTUITIVE EASY SOLUTION
|
intuitive-easy-solution-by-ramitgangwar-s0gi
|
\n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n \n\n\n\n# \u2B50 Intuition\nThe problem asks to count all substrings where at least one charact
|
ramitgangwar
|
NORMAL
|
2024-10-20T04:01:36.918112+00:00
|
2024-10-20T04:01:36.918151+00:00
| 275 | false |
<div align="center">\n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n</div>\n\n***\n\n# \u2B50 Intuition\nThe problem asks to count all substrings where at least one character appears at least `k` times. The key observation here is that, given a sliding window approach, once we find a substring where a character appears `k` times, extending this substring by adding more characters will still satisfy the condition.\n\n# \u2B50 Approach\n1. **Sliding Window**:\n - We use a sliding window approach with two pointers, `l` (left) and `r` (right). The `r` pointer expands the window by adding new characters, while the `l` pointer contracts the window when a valid substring is found.\n \n2. **Frequency Map**:\n - Maintain a frequency map `map` that keeps track of character frequencies within the current window `[l, r]`.\n \n3. **Counting Valid Substrings**:\n - For every right pointer `r`, we increment the frequency of the character at `s[r]` in the map.\n - If any character in the map has a frequency greater than or equal to `k`, all substrings starting from the current left pointer `l` up to the current right pointer `r` are valid.\n - When we find such valid substrings, we increment the count by `len - r` (which represents all possible valid substrings from the current window).\n - We then increment `l` to contract the window and continue searching for new substrings.\n\n4. **Return the Count**:\n - After the sliding window has processed the entire string, return the total count of valid substrings.\n\n# \u2B50 Complexity\n- **Time complexity**: \n The time complexity is **O(n)**, where `n` is the length of the string. Both pointers `l` and `r` traverse the string at most once.\n\n- **Space complexity**: \n The space complexity is **O(n)** due to the frequency map, which can store up to `n` characters in the worst case (if all characters in the string are distinct).\n\n# \u2B50 Code\n```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int count = 0;\n Map<Character, Integer> map = new HashMap<>();\n\n int l = 0, r = 0, len = s.length();\n\n while (r < len) {\n char ch = s.charAt(r);\n map.put(ch, map.getOrDefault(ch, 0) + 1);\n\n while (map.getOrDefault(ch, 0) >= k && l <= r) {\n count += len - r;\n\n char leftChar = s.charAt(l++);\n map.put(leftChar, map.get(leftChar) - 1);\n if (map.get(leftChar) == 0) map.remove(leftChar);\n }\n\n r++;\n }\n\n return count;\n }\n}\n```
| 6 | 0 |
['Sliding Window', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Easiest HashMap solution! Detailed Explanation provided.
|
easiest-hashmap-solution-detailed-explan-mrlc
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to store the frequency of each character in subtsring. So we need a map to coun
|
Varun_Haralalka
|
NORMAL
|
2024-10-26T16:19:54.408559+00:00
|
2024-10-26T16:19:54.408584+00:00
| 37 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to store the frequency of each character in subtsring. So we need a map to count. Now We go for the Brute force approach to form all substrings starting at each index. However we don\'t need to actually form them. We just need to store characters count in the map. If after addition of character, it\'s frequency is >= k, then going forward every addition to that substring is also valid. So we just store the index and break out. We add the no. of valid substrings it can form and return the count.\n\n\n# Complexity\n- Time complexity: O(N*N) * Time for Map(Avg. case O(1) for Unordered)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M) Maximum all characters needed to be stored in map.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int cnt=0;\n unordered_map<char, int> mpp;\n for(int i=0; i<s.length(); i++) {\n int found = -1;\n for(int j=i; j<s.length(); j++) {\n mpp[s[j]]++;\n if(mpp[s[j]] >= k) {\n found = j;\n break;\n }\n }\n cout<<found<<endl;\n if(found != -1) cnt += s.length() - found;\n mpp.clear();\n }\n return cnt;\n }\n};\n```
| 3 | 0 |
['Hash Table', 'String', 'C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Super Simple Sliding Window Count Java(O(n*n))
|
super-simple-sliding-window-count-javaon-81ub
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. find a window where
|
rajnarayansharma110
|
NORMAL
|
2024-10-20T08:20:13.090925+00:00
|
2024-10-20T08:20:13.090957+00:00
| 22 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. find a window where any freq>=k and add all the window from that point to n-1(n-r)\n# Complexity\n- Time complexity:O(n*n)\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```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int count = 0;\n int n = s.length();\n for (int l = 0; l < n; l++) {\n int[] freq = new int[26];\n for (int r = l; r < n; r++) {\n char c = s.charAt(r);\n freq[c - \'a\']++;\n if (freq[c - \'a\'] >= k) {\n count += (n - r);\n break;\n }\n }\n }\n return count;\n }\n}\n```
| 3 | 0 |
['Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Easy straightforward approach
|
easy-straightforward-approach-by-siddhuu-zi2k
|
Intuition\nTo solve the problem of counting substrings that contain at least k occurrences of any character, I initially thought about iterating through all pos
|
siddhuuse
|
NORMAL
|
2024-10-20T06:33:32.337802+00:00
|
2024-10-20T06:33:32.337838+00:00
| 146 | false |
# Intuition\nTo solve the problem of counting substrings that contain at least `k` occurrences of any character, I initially thought about iterating through all possible substrings of the given string `s`. For each substring, I could count the occurrences of each character and check if any of them met the requirement of at least `k` occurrences, Which is brute-force straightforward approach.\n\n# Approach\n- Start by initializing a counter `ans` to keep track of the number of valid substrings. Use a character count array `ct` of size 26 to count the occurrences of each character in the substring.\n\n- Iterate through each starting index `i` of the string `s`.For each starting index, iterate through the substring starting from `i` to the end of the string. Update the character count array for each character encountered.\n\n- Use a boolean flag `valid_sub` to indicate if a valid substring has been found. If the count of any character reaches `k`, set `valid_sub` to `True`.If `valid_sub` is `True`, increment the count of valid substrings `ans`.\n\n- After checking all possible substrings, return the total count of valid substrings.\n\n# Complexity\n- **Time Complexity**: `O(n^2)`, where `n` is the length of the string `s`, due to the nested loops iterating through each substring.\n\n- **Space Complexity**: `O(1)`, as the character count array has a fixed size of 26, regardless of the size of the input string.\n\n# Code\n```python3 []\nclass Solution:\n def numberOfSubstrings(self, s: str, k: int) -> int:\n ans=0\n for i in range(len(s)):\n ct=[0]*26\n valid_sub=False\n for j in range(i,len(s)):\n ct[ord(s[j])-ord(\'a\')]+=1\n if ct[ord(s[j])-ord(\'a\')]>=k:\n valid_sub=True\n if valid_sub:\n ans+=1\n return ans \n```
| 3 | 0 |
['String', 'Sliding Window', 'Python3']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Easy to understand approach using HashMap
|
easy-to-understand-approach-using-hashma-1yx2
|
Intuition\n Describe your first thoughts on how to solve this problem. \nGenerate all substring and maintain a hashmap to store count of letters and for every c
|
MainFrameKuznetSov
|
NORMAL
|
2024-10-20T04:27:32.396959+00:00
|
2024-10-20T04:27:32.396982+00:00
| 53 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGenerate all substring and maintain a hashmap to store count of letters and for every character appearing atleast k times, increase the count.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGreedily generate all substring and do as required.\nFor every \'i\', generate a new map and while iterating across the map,count the number of times any character apprears and if the count is greater than equal to $k$, increase count by 1.\n# Complexity\n- Time complexity:- $O(n^2)$ since all substrings are being constructed.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$ since the size of hashmap never exceeds 26.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int ans=0;\n for(int i=0;i<s.size();++i)\n {\n unordered_map<char,int>mp;\n for(int j=i;j<s.size();++j)\n {\n ++mp[s[j]];\n bool flag=0;\n for(auto iter:mp)\n {\n if(iter.second>=k)\n {\n //++ans;\n flag=1;\n break;\n }\n }\n if(flag==1)\n ++ans;\n }\n }\n return ans;\n }\n};\n```
| 3 | 0 |
['Hash Table', 'String', 'C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Java Clean Solution | Weekly Contest
|
java-clean-solution-weekly-contest-by-sh-0kbe
|
Code\njava []\nclass Solution {\n private boolean helper(int[] freq, int k){\n for(int f:freq){\n if(f>=k){\n return true;\n
|
Shree_Govind_Jee
|
NORMAL
|
2024-10-20T04:02:12.272003+00:00
|
2024-10-20T04:02:12.272037+00:00
| 225 | false |
# Code\n```java []\nclass Solution {\n private boolean helper(int[] freq, int k){\n for(int f:freq){\n if(f>=k){\n return true;\n }\n }\n return false;\n }\n \n public int numberOfSubstrings(String s, int k) {\n int n = s.length();\n \n int res=0;\n for(int i=0; i<n; i++){\n int[] freq = new int[26];\n for(int j=i; j<n; j++){\n char ch = s.charAt(j);\n freq[ch-\'a\']++;\n \n if(helper(freq, k)){\n res++;\n }\n }\n }\n return res;\n }\n}\n```
| 3 | 0 |
['Math', 'String', 'String Matching', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Brute force (All Substrings) >> Optimal (Sliding Window)
|
brute-force-all-substrings-optimal-slidi-mbb2
|
\n# Brute Force\n\n\nclass Solution {\npublic:\n \n int subs(const string &s, int k) {\n int n = s.length(); \n int cnt = 0;\n for (i
|
sirius_108
|
NORMAL
|
2024-10-20T04:02:09.912106+00:00
|
2024-10-20T04:08:29.280848+00:00
| 214 | false |
\n# Brute Force\n\n```\nclass Solution {\npublic:\n \n int subs(const string &s, int k) {\n int n = s.length(); \n int cnt = 0;\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j <= n; ++j) {\n\n string x = s.substr(i, j - i);\n unordered_map<char, int>mp;\n for(auto ch: x)\n mp[ch]++;\n for(auto el: mp)\n {\n if(el.second >= k)\n {\n cnt++;\n break;\n }\n }\n }\n }\n return cnt;\n }\n int numberOfSubstrings(string s, int k) {\n return subs(s, k);\n }\n};\n```\n# Optimal Using Sliding Window\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int n = s.length();\n int ans = 0;\n unordered_map<char, int> mp;\n int i = 0;\n for (int j = 0; j < n; ++j) {\n mp[s[j]]++;\n while (mp[s[j]] >= k) {\n ans += (n - j);\n mp[s[i]]--;\n i++;\n }\n }\n \n return ans;\n }\n};\n\n```
| 3 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Sliding window, O(n) java solution
|
sliding-window-on-java-solution-by-11abh-k020
|
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
|
11abhishekgg
|
NORMAL
|
2024-10-22T18:44:04.749578+00:00
|
2024-10-22T18:44:04.749630+00:00
| 34 | 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```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int result = 0, n = s.length(), start = 0;\n int countChar[] = new int[26];\n for (int i = 0; i < n; i++) {\n char c = s.charAt(i);\n countChar[c - \'a\']++;\n while (countChar[c - \'a\'] >= k) {\n result += n-i;\n countChar[s.charAt(start++) - \'a\']--;\n }\n }\n return result;\n }\n}\n```
| 2 | 0 |
['Java']
| 1 |
count-substrings-with-k-frequency-characters-i
|
Sliding window + counting | 8 ms - beats 100.00%
|
sliding-window-counting-8-ms-beats-10000-e12s
|
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\nwher
|
tigprog
|
NORMAL
|
2024-10-20T13:43:41.689640+00:00
|
2024-10-20T13:43:41.689677+00:00
| 186 | 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\nwhere `n = s.length <= 3000`\n\n# Code\n```python3 []\nclass Solution:\n def numberOfSubstrings(self, s: str, k: int) -> int:\n n = len(s)\n state = Counter()\n result = l = 0\n for r, char in enumerate(s):\n state[char] += 1\n while state[char] == k:\n result += n - r\n state[s[l]] -= 1\n l += 1\n return result\n```
| 2 | 0 |
['Two Pointers', 'Sliding Window', 'Counting', 'Python3']
| 1 |
count-substrings-with-k-frequency-characters-i
|
Simple Brute Force || Substring ✅
|
simple-brute-force-substring-by-harshsha-qatl
|
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
|
Harshsharma08
|
NORMAL
|
2024-10-20T04:24:16.720175+00:00
|
2024-10-20T04:24:16.720198+00:00
| 183 | 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```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int n = s.length(); \n int ans=0;\n for(int i=0;i<n;i++){\n Map<Character,Integer> map = new HashMap();\n int max=0;\n for(int j=i;j<n;j++){\n char ch = s.charAt(j);\n map.put(ch,map.getOrDefault(ch,0)+1);\n if(map.get(ch)>max) max = map.get(ch);\n if(max>=k) ans++;\n }\n }\n return ans;\n }\n}\n```
| 2 | 0 |
['String', 'C++', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
easy to learn
|
easy-to-learn-by-izer-bycv
|
Intuition\n Describe your first thoughts on how to solve this problem. \nwe have to count substring having at least one char fre. at leat k\n\n# Approach\n Desc
|
izer
|
NORMAL
|
2024-10-20T04:18:15.975261+00:00
|
2024-10-20T04:18:15.975287+00:00
| 9 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have to count substring having at least one char fre. at leat k\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfind all bossible substring \ncheck occurrence of char \nif we find even a case that is correct then add 1 for every substring \n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N*N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int n=s.size();\n long long int cnt=0;\n for(int i=0;i<n;i++){\n vector<int>mark(26,0);\n bool flag=0;\n for(int j=i;j<n;j++){\n mark[s[j]-\'a\']++;\n if(flag==1) cnt++;\n else if(mark[s[j]-\'a\']>=k){\n cnt++;\n flag=1;\n }\n }\n }\n return cnt;\n \n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
BEATS 90% || BEST BEGINNER CODE || SLIDING WINDOW || C++
|
beats-90-best-beginner-code-sliding-wind-p09t
|
Intuition\nTo find the number of substrings that contain at least \'k\' occurrences of each character, we can use the sliding window technique. By adjusting the
|
LeadingTheAbyss
|
NORMAL
|
2024-10-31T20:42:27.683959+00:00
|
2024-10-31T20:42:27.684001+00:00
| 38 | false |
# Intuition\nTo find the number of substrings that contain at least \'k\' occurrences of each character, we can use the sliding window technique. By adjusting the window size based on the character counts, we can efficiently count valid substrings.\n\n# Approach\n1. Initialize a variable `res` to the total number of substrings in the string.\n2. Use a sliding window with two pointers (`i` and `j`) to explore substrings.\n3. Maintain a hashmap to count the occurrences of each character within the window.\n4. Expand the window by moving `j` and updating character counts.\n5. If a character\'s count reaches `k`, shrink the window from the left by moving `i` to exclude characters and update the count.\n6. Calculate the number of valid substrings for each position of `j` and adjust `res` accordingly.\n7. Return the final count of valid substrings.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$ (since the hashmap will contain at most a fixed number of characters)\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int n = s.length(), res = (n + 1) * n / 2;\n unordered_map<char, int> mpp;\n for (int i = 0, j = 0; j < n; j++) {\n mpp[s[j]]++;\n while (mpp[s[j]] >= k)\n --mpp[s[i++]];\n res -= j - i + 1;\n }\n return res;\n }\n};\n```
| 1 | 0 |
['Hash Table', 'String', 'Sliding Window', 'C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
O(n) solution using sliding window and hash map. Intuition and approach explained. Beginner friendly
|
on-solution-using-sliding-window-and-has-e8pf
|
Intuition\n Describe your first thoughts on how to solve this problem. \nMy first thought on seeing "counting substrings satisfying some condition..." was to us
|
beluuga7
|
NORMAL
|
2024-10-25T17:55:01.359625+00:00
|
2024-10-25T17:59:32.278695+00:00
| 30 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on seeing "counting substrings satisfying some condition..." was to use sliding window technique.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince it involved frequency of characters, we would need a hashmap (or a simple array of size 26).\n- Have two variables i.e left and right to indicate the current window.\n- Initially both left and right are initialized to 0 (window size = 0).\n- Grow the window by incrementing the right pointer, at the same time, update the character frequency.\n- After updating the character frequency, check if the freq is >= k.\n- If yes then add all the substrings possible from s[left]....s[right]....s[n-1]. NOTE: The substrings are of the form : s[left]..s[right], s[left]...s[right]s[right+1], .... , s[left]...s[n-1].\n- On close observation, the number of such substrings is same as n - right i.e res += n - right . (n = s.length()).\n- Also keep shrinking the window by incrementing the left pointer till the condition fails.\n- Dont forget to update the character frequency while shrinking the window.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) \n {\n \n map<char, int> char_freq;\n int left, right, n, res;\n left = right = res = 0 ;\n n = s.length();\n\n for(right = 0 ; right < n ; right++)\n {\n char curr_char = s[right];\n char_freq[curr_char]++;\n\n while(char_freq[curr_char] >= k)\n {\n res += n - right; //Number of substrings starting from left index.\n char_freq[s[left]]--;\n left++;\n }\n\n }\n\n return res;\n \n }\n};\n```
| 1 | 0 |
['Hash Table', 'String', 'Sliding Window', 'C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
HashMap soln || O(n2) approach || Easy to understand
|
hashmap-soln-on2-approach-easy-to-unders-nws8
|
Complexity\n- Time complexity:\nO(n2)\n\n- Space complexity:\nO(n)\n\n# Code\njava []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n
|
Amar_1
|
NORMAL
|
2024-10-20T20:40:18.893529+00:00
|
2024-10-20T20:40:18.893555+00:00
| 7 | false |
# Complexity\n- Time complexity:\nO(n2)\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int count = 0;\n int n = s.length();\n\n for(int i = 0; i < s.length(); i++){\n HashMap<Character, Integer> map = new HashMap<>();\n for(int j = i; j < s.length(); j++){\n char ch = s.charAt(j);\n\n map.put(ch, map.getOrDefault(ch, 0)+1);\n if(map.get(ch) >= k){\n count += n-j;\n break;\n }\n }\n }\n\n return count;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Simple C++ Solution ✅✅
|
simple-c-solution-by-abhi242-t8wu
|
Code\ncpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int n=s.length();\n int ans=0;\n for(int i=0;i<n;i
|
Abhi242
|
NORMAL
|
2024-10-20T19:08:37.656797+00:00
|
2024-10-20T19:08:37.656818+00:00
| 16 | false |
# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int n=s.length();\n int ans=0;\n for(int i=0;i<n;i++){\n unordered_map<char,int> mp;\n for(int j=i;j<n;j++){\n mp[s[j]]++;\n if(mp[s[j]]>=k){\n ans+=(n-j);\n break;\n }\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
100% Beats || Sliding Window Approach || JAVA
|
100-beats-sliding-window-approach-java-b-wnp6
|
Intuition\n Describe your first thoughts on how to solve this problem. \n1. 100% BEATS\n2. Sliding Window Approach.\n\n# Approach\n Describe your approach to so
|
abhishekGaikwad96
|
NORMAL
|
2024-10-20T10:34:39.270961+00:00
|
2024-10-20T10:34:39.270980+00:00
| 48 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. 100% BEATS\n2. Sliding Window Approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Here we will use sliding window approach.And for every window we will contain an array of character which will contain the count of alphabets occuring in the substring and if any character appears more than k times we will increase the ans count.**\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int ans = 0;\n for(int i = 0 ; i<s.length(); i++){\n int[] ch = new int[26];\n for(int j = i ; j < s.length() ; j++){\n ch[s.charAt(j)-\'a\']++;\n for(int l : ch){\n if(l>=k){\n ans++;\n break;\n }\n }\n }\n }\n return ans;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
easiest JAVA solution by creating a frequency array.... BRUTE FORCE ....
|
easiest-java-solution-by-creating-a-freq-kun1
|
Intuition\n Describe your first thoughts on how to solve this problem. \napplying sliding window approach and keeping track of the frequency of characters and
|
coder_neeraj123
|
NORMAL
|
2024-10-20T09:26:30.359325+00:00
|
2024-10-20T09:26:30.359351+00:00
| 16 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\napplying sliding window approach and keeping track of the frequency of characters and counting valid substrings \n# Approach\n<!-- Describe your approach to solving the problem. -->\nfirst increase the size of the window until you get a substring that satisfies the given condition and calculate the no of substrings then minimize the size of the window and count the valid substrings utnill the condition voilates again and repeat this process till you reach the end of the string\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 numberOfSubstrings(String s, int k) {\n int l = 0;\n int r = 0;\n int count[] = new int[26];\n int n = s.length();\n int ans = 0;\n\n while (r < n) {\n char ch = s.charAt(r);\n count[ch - \'a\']++;\n\n boolean check = helper(count, k);\n\n if (check == true) {\n ans += n - r;\n\n while (l <= r) {\n\n count[s.charAt(l) - \'a\']--;\n l++;\n boolean check1 = helper(count, k);\n if (check1) {\n ans += n-r;\n } else {\n break;\n }\n }\n }\n r++;\n }\n\n return ans;\n\n }\n\n public static boolean helper(int count[], int k) {\n\n for (int i = 0; i < 26; i++) {\n if (count[i] == k) {\n return true;\n }\n }\n\n return false;\n }\n}\n```
| 1 | 0 |
['Java']
| 1 |
count-substrings-with-k-frequency-characters-i
|
Easy to understand Java Solution | O(n)
|
easy-to-understand-java-solution-on-by-v-c2y4
|
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
|
vg_85
|
NORMAL
|
2024-10-20T06:51:44.676497+00:00
|
2024-10-20T06:51:44.676529+00:00
| 17 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 numberOfSubstrings(String s, int k) {\n int f[]=new int[26];\n int i=0,j=0,n=s.length();\n int c=0;\n while(j<n){\n char ch=s.charAt(j);\n f[ch-\'a\']++;\n while(f[ch-\'a\']==k){\n f[s.charAt(i)-\'a\']--;\n i++;\n c+=n-j;\n }\n j++;\n }\n return c;\n }\n}\n```
| 1 | 0 |
['Sliding Window', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
✅✅✅🤫Easy Solution Optimised BruteForce
|
easy-solution-optimised-bruteforce-by-ro-hx0m
|
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
|
Royalking12
|
NORMAL
|
2024-10-20T06:46:48.179726+00:00
|
2024-10-20T06:46:48.179764+00:00
| 6 | 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 numberOfSubstrings(string s, int k) {\n int n=s.length();\n int ans=0;\n for(int i=0;i<n;i++){\n vector<int> V(26,0);\n bool flag=false; // if true means all next sequence contains more than k one repeated charter\n for(int j=i;j<n;j++){\n if(flag){\n ans+=(n-j);\n break;\n }\n V[s[j]-\'a\']++;\n for(auto &freq:V){\n if(freq>=k){\n flag=true;\n ans++;\n }\n }\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Sliding Window + HashMap
|
sliding-window-hashmap-by-himanshu_gahlo-t4jk
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1.Sliding Window Setup:
|
Himanshu_Gahlot
|
NORMAL
|
2024-10-20T06:01:31.538109+00:00
|
2024-10-20T06:01:31.538142+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. -->\n1.Sliding Window Setup: I maintain two pointers, i and j, where i represents the starting index and j represents the ending index of the current window (substring) under consideration. The goal is to explore all substrings starting from index i and ending at index j or beyond.\n\n2.Character Frequency Map: I use a HashMap to store the frequency of each character within the current window. As I expand the window by moving j to the right, I update the map with the frequency of the character at j.\n\n3.Condition Check: Whenever the character at j has appeared at least k times within the current window, I know that all substrings starting from i and ending at or after j are valid. This is because once a character in the window appears k times, all longer substrings will also have that character appearing k times or more.\n\n4.Counting Substrings: When the condition is met, I calculate the number of valid substrings by adding (n - j) to the count. This captures all possible substrings ending at j or beyond. Then, I shrink the window by moving the i pointer to the right and updating the frequency of the character at i.\n\n5.Repeat Process: I repeat this process, expanding the window by incrementing j and shrinking it as needed, until all valid substrings are counted.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(k)\n# Code\n```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int i=0;\n int j=0;\n int n=s.length();\n int count=0;\n HashMap<Character,Integer>mp=new HashMap<>();\n while(j<n){\n mp.put(s.charAt(j),mp.getOrDefault(s.charAt(j),0)+1);\n while(mp.get(s.charAt(j))>=k){\n count+=(n-j);\n mp.put(s.charAt(i),mp.get(s.charAt(i))-1);\n i++;\n }\n j++;\n\n }\n return count;\n\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Simple Solution || Sliding Window || Time: O(n) and Space: O(1)
|
simple-solution-sliding-window-time-on-a-nzu1
|
Approach\n Describe your approach to solving the problem. \n- Assume all are valid senarios and compute the total number of cases which is n(n + 1) / 2.\n- Now
|
godabauday
|
NORMAL
|
2024-10-20T05:44:54.665341+00:00
|
2024-10-20T05:44:54.665364+00:00
| 158 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Assume all are valid senarios and compute the total number of cases which is **n(n + 1) / 2**.\n- Now remove the substrings which are invalid.\n\n# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)** since only for fixed size of O(26)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def numberOfSubstrings(self, s: str, k: int) -> int:\n \n n = len(s)\n i = j = 0\n hashMap = defaultdict(int)\n count = int((n * (n + 1)) / 2)\n\n while j < n:\n # Count frequency of the alphabet\n hashMap[s[j]] += 1\n # Move i till the subtring is invalid\n while i <= j and hashMap[s[j]] == k:\n hashMap[s[i]] -= 1\n i += 1\n # Remove the invalid cases from computed result\n count -= (j - i + 1)\n j += 1\n\n return count\n```
| 1 | 0 |
['Array', 'Hash Table', 'Math', 'Sliding Window', 'Python3']
| 0 |
count-substrings-with-k-frequency-characters-i
|
TC : O(n), SC : O(26)
|
tc-on-sc-o26-by-konavivekramakrishna3747-6zi1
|
\n\n\n# Approach\n Describe your approach to solving the problem. \nTwo pointer approach (Sliding Window)\n\nTC : O(2n) ~ (n)\nSC : O(26) ~ O(1)\n\n\n\n# Code\n
|
kvrk
|
NORMAL
|
2024-10-20T05:11:44.557581+00:00
|
2024-10-20T05:11:44.557608+00:00
| 24 | false |
\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo pointer approach (Sliding Window)\n\nTC : O(2n) ~ (n)\nSC : O(26) ~ O(1)\n\n\n\n# Code\n```python3 []\nclass Solution:\n def numberOfSubstrings(self, s: str, k: int) -> int:\n \n freq = [0] * 26\n low = 0\n count = 0\n n = len(s)\n \n for high in range(n):\n \n index = ord(s[high]) - ord(\'a\')\n freq[index] += 1\n \n \n while freq[index] >= k:\n \n count += n - high\n \n char = s[low]\n char_index = ord(char) - ord(\'a\')\n low += 1\n \n freq[char_index] -= 1\n \n return count\n \n```
| 1 | 0 |
['Python3']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Sliding window approach with O(n) TC and O(1) SC
|
sliding-window-approach-with-on-tc-and-o-ufxu
|
Intuition\nSince its a substring problem, the intuition is to use sliding window\n\n# Approach\nEvery time a valid substring is found, all the characters after
|
spoorthibasu
|
NORMAL
|
2024-10-20T05:01:07.433337+00:00
|
2024-10-20T05:14:06.380721+00:00
| 22 | false |
# Intuition\nSince its a substring problem, the intuition is to use sliding window\n\n# Approach\nEvery time a valid substring is found, all the characters after the end of that substring is still valid until the end of the given string. \nEx: abacb and k = 2,\nif, "aba" substring is valid\nthen all the substrings till the end of the string is valid,\ni.e, aba, abac, abacb\n\nso add these to the result with,\nresult += s.length() - end of current valid substring\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int left = 0;\n int result = 0;\n int[] count = new int[26];\n\n for(int i = 0; i< s.length(); i++) {\n char ch = s.charAt(i);\n count[ch -\'a\']++;\n\n while(count[ch - \'a\'] == k) {\n result += s.length() - i;\n char atLeft = s.charAt(left);\n count[atLeft - \'a\']--;\n left++;\n }\n }\n\n return result;\n }\n}\n\n//TC: O(N)\n//SC: O(1)\n```
| 1 | 0 |
['Sliding Window', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
✨Easy Approach CPP ||💪Beats 100.00% ||✅✅☑️☑️
|
easy-approach-cpp-beats-10000-by-swapnee-w5ca
|
Approach:\n# Initialize Variables:\n\n- Use an integer totalCount to keep track of the total valid substrings.\n- Use a vector of size 26 (for each lowercase le
|
swapneel_singh
|
NORMAL
|
2024-10-20T04:13:34.808064+00:00
|
2024-10-20T04:13:34.808096+00:00
| 235 | false |
# Approach:\n# Initialize Variables:\n\n- Use an integer totalCount to keep track of the total valid substrings.\n- Use a vector<int> of size 26 (for each lowercase letter) to store the frequency of characters in the current sliding window.\n- Set up two pointers, left and right, to represent the current window of characters in the string.\n# Expand the Window:\n\n- Iterate over the string with the right pointer.\n- For each character, increment its frequency in the freq array.\n# Check Frequency Condition:\n\n- Use a loop to check if any character in the freq array has a frequency of at least k.\n- If the condition is met, count all substrings starting from left to right, which is calculated as (n - right) where n is the length of the string.\n# Contract the Window:\n\n- After counting valid substrings, move the left pointer to contract the window and decrement the frequency of the character at the left pointer.\n# Return the Result:\n\n- After processing the entire string, return totalCount as the result.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numberOfSubstrings(string s, int k) {\n int n = s.length();\n int totalCount = 0;\n vector<int> freq(26, 0); // Frequency of each character in the current window\n int left = 0; // Left pointer of the sliding window\n \n // Iterate over each character with right pointer expanding the window\n for (int right = 0; right < n; right++) {\n // Update frequency of the current character\n freq[s[right] - \'a\']++;\n \n // Check if there is any character with frequency >= k\n while (any_of(freq.begin(), freq.end(), [k](int count) { return count >= k; })) {\n // If condition met, count all substrings from left to the current right\n totalCount += (n - right);\n // Contract the window from the left side by moving left pointer\n freq[s[left] - \'a\']--;\n left++;\n }\n }\n \n return totalCount;\n }\n};\n\n```
| 1 | 0 |
['C++']
| 2 |
count-substrings-with-k-frequency-characters-i
|
C++ | 100% beats
|
c-100-beats-by-gourav_1_2_3_r-p8j8
|
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
|
Gourav_1_2_3_r_
|
NORMAL
|
2024-10-20T04:10:19.160771+00:00
|
2024-10-20T04:10:19.160823+00:00
| 9 | 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 numberOfSubstrings(string s, int k) {\n int ans = 0;\n unordered_map<char, int> mp;\n int l = 0; \n for (int r = 0; r < s.size(); r++) {\n mp[s[r]]++;\n while (mp[s[r]] >= k) {\n ans += s.size() - r; \n mp[s[l]]--; \n l++; \n }\n }\n\n return ans;\n }\n};\n\n```
| 1 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
13MS || 100 % || Optimised solution || Java Solution
|
13ms-100-optimised-solution-java-solutio-uc87
|
Intuition\nWe are tasked with finding the number of substrings where at least one character appears k or more times. The key idea is to use a sliding window tec
|
yallavamsipavan1234
|
NORMAL
|
2024-10-20T04:10:14.990949+00:00
|
2024-10-20T04:10:14.990984+00:00
| 34 | false |
# Intuition\nWe are tasked with finding the number of substrings where at least one character appears k or more times. The key idea is to use a sliding window technique to explore every substring, and for each substring, we check if a character appears k or more times. If such a substring is found, all suffix substrings starting from that point will also meet the condition.\n\n# Approach\n- `Sliding Window`: The outer loop (with start as the left boundary) explores every starting position for substrings. The inner loop (with end as the right boundary) increments the window size while checking how often each character appears within the current substring.\n- `Counting Frequency`: A frequency array arr of size 26 is used to keep track of the number of occurrences of each character in the current window.\n- `Termination`: As soon as a character appears k or more times in the substring, we count all substrings that can be formed starting from start to the end of the string, since those will also meet the requirement.\n- `Optimization`: Once we find such a substring, we can break the inner loop early, as any longer substrings starting from start will satisfy the condition by including more characters.\n\n# Complexity\n- Time complexity: `O(N^2)`\n\n- Space complexity: `O(1)`\n\n# Code\n```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n int n = s.length();\n int[] arr = new int[26];\n int start = 0, end = 0;\n int ans = 0;\n while(start < n) {\n Arrays.fill(arr, 0);\n end = start;\n while(end < n) {\n arr[s.charAt(end)-\'a\']++;\n if(arr[s.charAt(end)-\'a\'] >= k) {\n ans += (n - end);\n break;\n }\n end++;\n }\n if(end == n) break;\n start++;\n }\n return ans;\n }\n}\n```
| 1 | 0 |
['Array', 'String', 'String Matching', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Basic approach, Direct Way
|
basic-approach-direct-way-by-sai116-qvfw
|
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
|
Sai116
|
NORMAL
|
2024-10-20T04:01:29.949791+00:00
|
2024-10-20T05:37:26.877356+00:00
| 54 | 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```java []\nclass Solution {\n public int numberOfSubstrings(String s, int k) {\n HashMap<Character,Integer> map=new HashMap<>();\n int count=0;\n for(int i=0;i<s.length();i++)\n {\n map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);\n if(map.get(s.charAt(i))>=k)count++;\n int max=Math.max(map.get(s.charAt(i)),0);\n for(int j=i+1;j<s.length();j++)\n {\n char c=s.charAt(j);\n map.put(c,map.getOrDefault(c,0)+1);\n if(map.get(c)>=k || max>=k){count++;} //To see whether there is a character which is repeating atleast k times\n max=Math.max(map.get(c),max);\n }\n map.clear();\n }\n return count;\n\n }\n}\n```
| 1 | 0 |
['Hash Table', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
sliding window beats 100%
|
sliding-window-beats-100-by-kakileti_mur-s64c
|
IntuitionApproach
Initialize sliding window:
Use unordered_map m to track character frequencies.
Set left = 0, and count = 0 for valid substrings.
Expand t
|
kakileti_Murari
|
NORMAL
|
2025-04-11T10:10:27.943626+00:00
|
2025-04-11T10:10:27.943626+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
1. **Initialize sliding window**:
- Use `unordered_map m` to track character frequencies.
- Set `left = 0`, and `count = 0` for valid substrings.
2. **Expand the window from left to right**:
- For each character `s[i]`, increment its frequency in `m`.
3. **When current character occurs `k` times**:
- Every substring from current `i` to end (`n-i` substrings) is valid.
- Shrink the window from the left until `m[s[i]] < k`.
4. **Return total count** of such valid substrings.
# Complexity
- Time complexity:O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int numberOfSubstrings(string s, int k) {
unordered_map<int,int>m;
int n=s.length();
int count=0;
int left=0;
for(int i=0;i<n;i++)
{
m[s[i]]++;
while(m[s[i]]==k)
{
count+=n-i;
m[s[left]]--;
left++;
}
}
return count;
}
};
```
| 0 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
O(n) Solution beat 100%
|
on-solution-beat-100-by-nitin_patel04-ivek
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
nitin_patel04
|
NORMAL
|
2025-04-04T08:43:04.287715+00:00
|
2025-04-04T08:43:04.287715+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:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int numberOfSubstrings(string s, int k) {
int count=0;
int left=0;
int n=s.length();
unordered_map<char,int>mp;
for(int r =0;r<s.size();r++){
mp[s[r]]++;
while(mp[s[r]]>=k){
count+=n-r;
cout<<count<<endl;
mp[s[left]]--;
left++;
}
}
return count;
}
};
```
| 0 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
easy sliding window (java)
|
easy-sliding-window-java-by-dpasala-kyho
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
dpasala
|
NORMAL
|
2025-04-03T17:45:10.476820+00:00
|
2025-04-03T17:45:10.476820+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int numberOfSubstrings(String s, int k) {
int n = s.length();
int total = (n + 1) * n / 2;
int left = 0;
int[] freq = new int[26];
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
freq[c - 'a']++;
while (freq[c - 'a'] >= k) freq[s.charAt(left++) - 'a']--;
total -= i - left + 1;
}
return total;
}
}
```
| 0 | 0 |
['Sliding Window', 'Java']
| 0 |
count-substrings-with-k-frequency-characters-i
|
A bit different interesting approach (not sliding window)
|
a-bit-different-interesting-approach-not-v63v
|
IntuitionThis solution tracks positions where characters reach frequency k, then counts valid substrings by determining all possible starting positions that pai
|
shmirrakhimov
|
NORMAL
|
2025-03-20T10:32:45.825042+00:00
|
2025-03-20T10:32:45.825042+00:00
| 2 | false |
# Intuition
This solution tracks positions where characters reach frequency k, then counts valid substrings by determining all possible starting positions that pair with each ending position.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
1) Track Character Positions: For each character, store its positions in the string
2) Mark Ending Positions: When a character appears k times, mark where its frequency reaches k
3) Count Valid Substrings: For each potential starting position (where a character reaches frequency k), count all valid substrings that can end at any position after it
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
The key insight is avoiding checking each possible substring individually by precomputing valid ending positions and then efficiently counting all valid combinations.
# Code
```javascript []
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
var numberOfSubstrings = function(s, k) {
let res = 0;
let arr = new Array(s.length).fill(Infinity);
let count = new Array(26).fill(null).map(() => []);
for(let i = 0; i < s.length; i++){
let c = s.charCodeAt(i) - 97;
count[c].push(i);
let len = count[c].length;
if(len >= k) arr[count[c][len - k]] = i;
}
for(let i = 0; i < arr.length; i++){
if(arr[i] == Infinity) continue;
let end = s.length;
let j = i - 1;
res += end - arr[i];
while(j >= 0 && arr[j] > arr[i]){
if(arr[j] < end) end = arr[j];
res += end - arr[i];
j--;
}
}
return res;
};
```
| 0 | 0 |
['Hash Table', 'String', 'JavaScript']
| 0 |
count-substrings-with-k-frequency-characters-i
|
C++ sliding window approach Time: O(n) Space: O(n) beat 100%!!
|
c-sliding-window-approach-time-on-space-sne35
|
Approachkeeps open window till find there is a char freq is greater than k,
and all the subarray including current one will all be the answer.Once we update the
|
chienwade5960
|
NORMAL
|
2025-03-12T05:40:50.850763+00:00
|
2025-03-12T05:40:50.850763+00:00
| 1 | false |
# Approach
<!-- Describe your approach to solving the problem. -->
keeps open window till find there is a char freq is greater than k,
and all the subarray including current one will all be the answer.
Once we update the answer then close window to check the condition still meet or not
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
# Code
```cpp []
class Solution {
public:
int numberOfSubstrings(string s, int k) {
// setup freq table and the window pointer and answer counter
unordered_map<char, int> table;
int left = 0;
int right = 0;
int ans = 0;
// sliding window
while(right < s.size()){
// update freq table
table[s[right]]++;
// find at least one char >= k times
// get the subarray ans (all possible sub to the right)
// close window
while(table[s[right]] >= k){
ans += s.size() - right;
table[s[left]]--;
left++;
}
// open window
right++;
}
return ans;
}
};
```
| 0 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
C++ | sliding window
|
c-sliding-window-by-kena7-p50w
|
ApproachSliding windowComplexity
Time complexity:
O(n*26)
Space complexity:
O(26)
Code
|
kenA7
|
NORMAL
|
2025-03-08T13:41:46.171736+00:00
|
2025-03-08T13:41:46.171736+00:00
| 1 | false |
# Approach
Sliding window
# Complexity
- Time complexity:
O(n*26)
- Space complexity:
O(26)
# Code
```cpp []
class Solution {
public:
bool good(vector<int> &count,int k)
{
for(auto &x:count)
if(x>=k)
return true;
return false;
}
int numberOfSubstrings(string s, int k)
{
vector<int>count(26,0);
int n=s.size(),j=0,i=0,res=0;
while(j<n)
{
count[s[j]-'a']++;
while(good(count,k))
{
res+=(n-j);
count[s[i]-'a']--;
i++;
}
j++;
}
return res;
}
};
```
| 0 | 0 |
['C++']
| 0 |
count-substrings-with-k-frequency-characters-i
|
Golang solution
|
golang-solution-by-sudarshan_a_m-izuk
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Sudarshan_A_M
|
NORMAL
|
2025-02-28T05:12:23.547040+00:00
|
2025-02-28T05:12:23.547040+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```golang []
func numberOfSubstrings(s string, k int) int {
n := len(s)
var res int
var countMap = make(map[string]int)
start, end := 0, 0
for end < n {
countMap[string(s[end])]++
if CheckMap(countMap, k) {
tempres := (n - end)
res += tempres
track := 0
for CheckMap(countMap, k) {
track++
countMap[string(s[start])]--
start++
}
if track-1 >= 0 {
res = res + ((track - 1) * (tempres))
}
}
end++
}
return res
}
func CheckMap(mp map[string]int, k int) bool {
for _, val := range mp {
if val >= k {
return true
}
}
return false
}
```
| 0 | 0 |
['Go']
| 0 |
count-substrings-with-k-frequency-characters-i
|
easy solution
|
easy-solution-by-owenwu4-z08x
|
Intuitionuse n2ApproachComplexity
Time complexity:
Space complexity:
Code
|
owenwu4
|
NORMAL
|
2025-02-19T02:12:24.412050+00:00
|
2025-02-19T02:12:24.412050+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
use n2
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def numberOfSubstrings(self, s: str, k: int) -> int:
c = Counter()
res = 0
#{a: 2}
#{a: 2, b: 1}
for i in range(len(s)):
c.clear()
biggest = 0
for j in range(i, len(s)):
c[s[j]] += 1
if c[s[j]] >= biggest:
biggest = c[s[j]]
if biggest >= k:
res += 1
return res
```
| 0 | 0 |
['Python3']
| 0 |
count-substrings-with-k-frequency-characters-i
|
100% Java Solution✔✔✔⚡⚡⚡
|
100-java-solution-by-shubhamrathore24-0jux
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
shubhamrathore24
|
NORMAL
|
2025-02-17T19:05:23.308993+00:00
|
2025-02-17T19:05:23.308993+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int numberOfSubstrings(String s, int k) {
HashMap<Character,Integer>map=new HashMap<>();
int n=s.length();
int ans=0;
int left=0;
for(int i=0; i<n; i++){
char c=s.charAt(i);
map.put(c,map.getOrDefault(c,0)+1);
if(map.get(c)==k){
while(map.get(c)==k){
ans+=n-i;
char ch=s.charAt(left);
map.put(ch,map.get(ch)-1);
left++;
}
}
}
return ans;
}
}
```
| 0 | 0 |
['Java']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.