Maximum Number of Occurrences of a Substring in C++


Suppose we have a string s, we have to find the maximum number of occurrences of any substring that satisfies the following rules −

  • The number of distinct characters in the substring must be less than or equal to maxLetters.
  • The substring size must be in range minSize and maxSize inclusive.

So if the input is like − “aababcaab”, maxLetters = 2, minSize = 3 and maxSize = 4, then the output will be 2. The substring "aab" has 2 occurrences in the original string. This satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).

To solve this, we will follow these steps −

  • Define a map m
  • for sz in range minSize to maxSize
    • make a map x, create a temp, initially empty
    • for i in range 0 to sz – 1
      • increase x[s[i]] by 1
      • temp := temp + s[i]
    • for j is 0, i in range sz to size of s – 1, increase i and j by 1
      • if size of x <= maxLetters, then increase m[temp] by 1
      • decrease x[temp[0]] by 1
      • if x[temp[0]] is 0, then delete temp[0] from x
      • delete first and second element of temp from the temp itself
      • increase x[s[i]] by 1
      • temp := temp + s[i]
    • if size of x <= maxLetters, then increase m[temp] by 1
  • ans := 0
  • while map m has some elements, then
    • ans := max of ans and value of ith key-value pair
  • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int maxFreq(string s, int maxLetters, int minSize, int maxSize) {
      unordered_map <string ,int > m;
      for(int sz = minSize; sz <= minSize; sz++){
         unordered_map <char, int> x;
         string temp ="";
         for(int i = 0; i < sz; i++){
            x[s[i]]++;
            temp += s[i];
         }
         for(int j = 0, i = sz; i < s.size(); i++, j++){
            if(x.size() <= maxLetters){
               m[temp]++;
            }
            x[temp[0]]--;
            if(x[temp[0]] == 0)x.erase(temp[0]);
            temp.erase(temp.begin(),temp.begin() + 1);
            x[s[i]]++;
            temp += s[i];
         }
         if(x.size() <= maxLetters){
            m[temp]++;
         }
      }
      int ans = 0;
      unordered_map <string ,int > :: iterator i = m.begin();
      while(i != m.end()){
         ans = max (ans, i->second);
         i++;
      }
      return ans;
   }
};
main(){
   Solution ob;
   cout << (ob.maxFreq("aababcaab",2,3,4));
}

Input

"aababcaab"
2
3
4

Output

2

Updated on: 30-Apr-2020

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements