Skip to content
Related Articles

Related Articles

Python – Maximum Consecutive Substring Occurrence

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 05 Sep, 2022
View Discussion
Improve Article
Save Article

Sometimes, while working with python, we can have a problem in which we need to check for substrings occurring in consecutive repetition. This can have application in data domains. Lets discuss a way in which this task can be performed. 

Method : Using max() + re.findall() The combination of above methods can be used to perform this task. In this, we extract the substrings repetitions using  findall() and extract the maximum of them using max(). 

Python3




# Python3 code to demonstrate working of
# Maximum Consecutive Substring Occurrence
# Using max() + re.findall()
import re
 
# initializing string
test_str = 'geeksgeeks are geeks for all geeksgeeksgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing subs
sub_str = 'geeks'
 
# Maximum Consecutive Substring Occurrence
# Using max() + re.findall()
res = max(re.findall('((?:' + re.escape(sub_str) + ')*)', test_str), key = len)
 
# printing result
print("The maximum run of Substring : " + res)

Output : 

The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
The maximum run of Substring : geeksgeeksgeeks

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!