Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count Occurrences of a Given Character in a String
Next article icon

Maximum consecutive occurrences of a string in another given string

Last Updated : 12 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings str1 and str2, the task is to count the maximum consecutive occurrences of the string str2 in the string str1.

Examples:

Input: str1 = “abababcba”, str2 = “ba” 
Output: 2 
Explanation: String str2 occurs consecutively in the substring { str[1], …, str[4] }. Therefore, the maximum count obtained is 2

Input: str1 = “ababc”, str2 = “ac” 
Output: 0 
Explanation: 
Since str2 is not present as a substring in str1, the required output is 0.

Approach: Follow the steps below to solve the problem:

  • Initialize a variable, say cntOcc, to store the count of occurrences of str2 in the string str1.
  • Iterate over the range [CntOcc, 1]. For every ith value in the iteration, concatenate the string str2 i times and check if the concatenated string is a substring of the string str1 or not. The first ith value for which it is found to be true, print it as the required answer.

Below is the implementation:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
 
int countFreq(string& pat, string& txt)
{
    int M = pat.length();
    int N = txt.length();
    int res = 0;
 
    // A loop to slide pat[] one by one
    for(int i = 0; i <= N - M; i++)
    {
         
        // For current index i, check
        // for pattern match
        int j;
        for(j = 0; j < M; j++)
            if (txt[i + j] != pat[j])
                break;
 
        // If pat[0...M-1] = txt[i, i+1, ...i+M-1]
        if (j == M)
        {
            res++;
            j = 0;
        }
    }
    return res;
}
 
// Function to count the maximum
// consecutive occurrence of the
// string str2 in the string str1
int maxRepeating(string str1, string str2)
{
     
    // Stores the count of consecutive
    // occurrences of str2 in str1
    int cntOcc = countFreq(str2, str1);
     
    // Concatenate str2 cntOcc times
    string Contstr = "";
 
    for(int i = 0; i < cntOcc; i++)
        Contstr += str2;
 
    // Iterate over the string str1
    // while Contstr is not present in str1
    size_t found = str1.find(Contstr);
     
    while (found == string::npos)
    {
        found = str1.find(Contstr);
         
        // Update cntOcc
        cntOcc -= 1;
 
        // Update Contstr
        Contstr = "";
         
        for(int i = 0; i < cntOcc; i++)
            Contstr += str2;
    }
    return cntOcc;
}
 
// Driver Code
int main()
{
    string str1 = "abababc";
    string str2 = "ba";
     
    cout << maxRepeating(str1, str2);
 
    return 0;
}
 
// This code is contributed by grand_master
 
 

Java




// Java program to implement
// the above approach
 
import java.util.*;
class GFG
{
static int countFreq(String pat, String txt)
{
    int M = pat.length();
    int N = txt.length();
    int res = 0;
 
    // A loop to slide pat[] one by one
    for(int i = 0; i <= N - M; i++)
    {
         
        // For current index i, check
        // for pattern match
        int j;
        for(j = 0; j < M; j++)
            if (txt.charAt(i + j) != pat.charAt(j))
                break;
 
        // If pat[0...M-1] = txt[i, i+1, ...i+M-1]
        if (j == M)
        {
            res++;
            j = 0;
        }
    }
    return res;
}
 
// Function to count the maximum
// consecutive occurrence of the
// String str2 in the String str1
static int maxRepeating(String str1, String str2)
{
     
    // Stores the count of consecutive
    // occurrences of str2 in str1
    int cntOcc = countFreq(str2, str1);
     
    // Concatenate str2 cntOcc times
    String Contstr = "";
 
    for(int i = 0; i < cntOcc; i++)
        Contstr += str2;
 
    // Iterate over the String str1
    // while Contstr is not present in str1
    boolean found = str1.contains(Contstr);
     
    while (!found)
    {
        found = str1.contains(Contstr);
         
        // Update cntOcc
        cntOcc -= 1;
 
        // Update Contstr
        Contstr = "";
         
        for(int i = 0; i < cntOcc; i++)
            Contstr += str2;
    }
    return cntOcc;
}
 
// Driver Code
public static void main(String[] args)
{
    String str1 = "abababc";
    String str2 = "ba"; 
    System.out.print(maxRepeating(str1, str2));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to count the maximum
# consecutive occurrence of the
# string str2 in the string str1
def maxRepeating(str1, str2):
 
    # Stores the count of consecutive
    # occurrences of str2 in str1
    cntOcc = str1.count(str2)
 
    # Concatenate str2 cntOcc times
    Contstr = str2 * cntOcc
 
     
    # Iterate over the string str1
    # while Contstr is not present in str1
    while(Contstr not in str1):
 
        # Update cntOcc
        cntOcc -= 1
         
       # Update Contstr
        Contstr = str2 * cntOcc
         
    return cntOcc
 
# Driver Code
if __name__ =="__main__":
  str1 = "abababc"
  str2 = "ba"
  print(maxRepeating(str1, str2))
  
 
 

C#




// C# program to implement
// the above approach
using System;
 
class GFG
{
static int countFreq(String pat, String txt)
{
    int M = pat.Length;
    int N = txt.Length;
    int res = 0;
 
    // A loop to slide pat[] one by one
    for(int i = 0; i <= N - M; i++)
    {
         
        // For current index i, check
        // for pattern match
        int j;
        for(j = 0; j < M; j++)
            if (txt[i + j] != pat[j])
                break;
 
        // If pat[0...M-1] = txt[i, i+1, ...i+M-1]
        if (j == M)
        {
            res++;
            j = 0;
        }
    }
    return res;
}
 
// Function to count the maximum
// consecutive occurrence of the
// String str2 in the String str1
static int maxRepeating(String str1, String str2)
{
     
    // Stores the count of consecutive
    // occurrences of str2 in str1
    int cntOcc = countFreq(str2, str1);
     
    // Concatenate str2 cntOcc times
    String Contstr = "";
 
    for(int i = 0; i < cntOcc; i++)
        Contstr += str2;
 
    // Iterate over the String str1
    // while Contstr is not present in str1
    bool found = str1.Contains(Contstr);   
    while (!found)
    {
        found = str1.Contains(Contstr);
         
        // Update cntOcc
        cntOcc -= 1;
 
        // Update Contstr
        Contstr = "";
         
        for(int i = 0; i < cntOcc; i++)
            Contstr += str2;
    }
    return cntOcc;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str1 = "abababc";
    String str2 = "ba"; 
    Console.Write(maxRepeating(str1, str2));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
      // JavaScript program to implement
      // the above approach
      function countFreq(pat, txt) {
        var M = pat.length;
        var N = txt.length;
        var res = 0;
 
        // A loop to slide pat[] one by one
        for (var i = 0; i <= N - M; i++) {
          // For current index i, check
          // for pattern match
          var j;
          for (j = 0; j < M; j++)
              if (txt[i + j] !== pat[j])
                break;
 
          // If pat[0...M-1] = txt[i, i+1, ...i+M-1]
          if (j === M) {
            res++;
            j = 0;
          }
        }
        return res;
      }
 
      // Function to count the maximum
      // consecutive occurrence of the
      // String str2 in the String str1
      function maxRepeating(str1, str2) {
        // Stores the count of consecutive
        // occurrences of str2 in str1
        var cntOcc = countFreq(str2, str1);
 
        // Concatenate str2 cntOcc times
        var Contstr = "";
 
        for (var i = 0; i < cntOcc; i++)
            Contstr += str2;
 
        // Iterate over the String str1
        // while Contstr is not present in str1
        var found = str1.includes(Contstr);
        while (!found) {
          found = str1.includes(Contstr);
 
          // Update cntOcc
          cntOcc -= 1;
 
          // Update Contstr
          Contstr = "";
 
          for (var i = 0; i < cntOcc; i++)
              Contstr += str2;
        }
        return cntOcc;
      }
 
      // Driver Code
      var str1 = "abababc";
      var str2 = "ba";
      document.write(maxRepeating(str1, str2));
</script>
 
 
Output: 
2

 

Time Complexity: O(N2), as we are using nested loops for traversing N*N times.
Auxiliary Space: O(N), as we are using extra space.



Next Article
Count Occurrences of a Given Character in a String
author
saikumarkudikala
Improve
Article Tags :
  • DSA
  • Mathematical
  • Searching
  • Strings
  • substring
Practice Tags :
  • Mathematical
  • Searching
  • Strings

Similar Reads

  • Maximum consecutive repeating character in string
    Given a string s, the task is to find the maximum consecutive repeating character in the string. Note: We do not need to consider the overall count, but the count of repeating that appears in one place. Examples: Input: s = "geeekk"Output: eExplanation: character e comes 3 times consecutively which
    11 min read
  • Count occurrences of a string that can be constructed from another given string
    Given two strings str1 and str2 where str1 being the parent string. The task is to find out the number of string as str2 that can be constructed using letters of str1. Note: All the letters are in lowercase and each character should be used only once. Examples: Input: str1 = "geeksforgeeks", str2 =
    5 min read
  • Count Occurrences of a Given Character in a String
    Given a string S and a character 'c', the task is to count the occurrence of the given character in the string. Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str. Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times i
    6 min read
  • Count of Distinct Substrings occurring consecutively in a given String
    Given a string str, the task is to find the number of distinct substrings that are placed consecutively in the given string. Examples: Input: str = "geeksgeeksforgeeks" Output: 2 Explanation: geeksgeeksforgeeks -> {"geeks"} geeksgeeksforgeeks -> {"e"} Only one consecutive occurrence of "e" is
    14 min read
  • Find maximum occurring character in a string
    Given string str. The task is to find the maximum occurring character in the string str. Examples: Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the string Input: testOutput: tExplanation: 't' occurs 2 times in the string Return the maximum occurring character in an input string us
    9 min read
  • Frequency of maximum occurring subsequence in given string
    Given a string str of lowercase English alphabets, our task is to find the frequency of occurrence a subsequence of the string which occurs the maximum times. Examples: Input: s = "aba" Output: 2 Explanation: For "aba", subsequence "ab" occurs maximum times in subsequence 'ab' and 'aba'. Input: s =
    6 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • Minimize partitions in given string to get another string
    Given two strings A and B, print the minimum number of slices required in A to get another string B. In case, if it is not possible to get B from A, then print "-1". Examples : Input: A = "geeksforgeeks", B = "ksgek"Output: 5Explanation: g | ee | ks | forge | ek | s : minimum 5 slices are required t
    15+ min read
  • Maximum repeating character for every index in given String
    Given string str consisting of lowercase alphabets, the task is to find the maximum repeating character obtained for every character of the string. If for any index, more than one character has occurred a maximum number of times, then print the character which had occurred most recently. Examples: I
    6 min read
  • Count occurrences of substring X before every occurrence of substring Y in a given string
    Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First o
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences