Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Longest Run of given Character in String
Next article icon

Python | Longest Run of given Character in String

Last Updated : 23 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using loop This is brute force method in which we can perform this task. In this, we run a loop over the String and keep on memorizing the maximum whenever the run occurs. 

Python3
# Python3 code to demonstrate working of  # Longest Run of Character in String  # Using loop   # initializing string  test_str = 'geeksforgeeeks'  # printing original string  print("The original string is : " + test_str)   # initializing K  K = 'e'  # Longest Run of Character in String  # Using loop  res = 0 cnt = 0 for chr in test_str:      if chr == K:          cnt += 1     else:          res = max(res, cnt)          cnt = 0 res = max(res, cnt)   # printing result  print("Longest Run length of K : " + str(res))  

Output
The original string is : geeksforgeeeks Longest Run length of K : 3

Time Complexity: O(n)

Auxiliary Space: O(1)

  Method #2 : Using max() + re.findall() This is one liner way in which this problem can be solved. In this, we find the maximum of all runs found using findall(). 

Python3
# Python3 code to demonstrate working of  # Longest Run of Character in String  # Using max() + re.findall()  import re   # initializing string  test_str = 'geeksforgeeeks'  # printing original string  print("The original string is : " + test_str)   # initializing K  K = 'e'  # Longest Run of Character in String  # Using max() + re.findall()  res = len(max(re.findall(K + '+', test_str), key = len))   # printing result  print("Longest Run length of K : " + str(res))  

Output
The original string is : geeksforgeeeks Longest Run length of K : 3

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

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #3 : Using while loop and max(),pop() methods

Python3
# Python3 code to demonstrate working of # Longest Run of Character in String # Using loop  # initializing string test_str = 'geeksforgeeeeeks'  # printing original string print("The original string is : " + test_str)  # initializing K K = 'e' res=[] i=1 while(K in test_str):     K="e"*i     res.append(i)     i+=1 res.pop() ma=max(res) # printing result print("Longest Run length of K : " + str(ma)) 

Output
The original string is : geeksforgeeeeeks Longest Run length of K : 5

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #4 : Using recursive method

Python3
# Python3 code to demonstrate working of # Longest Run of Character in String # Using recursive function  def longest_run_recursive(string, k, i=0):     if i == len(string):  #base condition         return 0     if string[i] == k:         return 1 + longest_run_recursive(string, k, i + 1)     else:         return 0    # initializing string test_str = 'geeksforgeeeeeks'  # printing original string print("The original string is : " + test_str)  # initializing K k = 'e'  longest_run = max(longest_run_recursive(test_str, k, i) for i in range(len(test_str)))  # printing result print("Longest Run length of K : " + str(longest_run)) #this code contributed by tvsk 

Output
The original string is : geeksforgeeeeeks Longest Run length of K : 5

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using itertools groupby()

  • Import the itertools module.
  • Initialize the input string test_str and the target character K.
  • Use itertools.groupby() to group the characters in test_str into consecutive runs of the same character.
  • For each run of the character K, append the length of the run to a list called counts.
  • Find the maximum value in counts, which represents the length of the longest run of the character K in test_str.
  • Print the result.
Python3
import itertools test_str = 'geeksforgeeeks' K = 'e' groups = itertools.groupby(test_str) counts = [] for k, g in groups:     if k == K:         counts.append(len(list(g))) longest_run = max(counts) print("Longest Run length of K : " + str(longest_run))  #This code is contributed by Vinay Pinjala. 

Output
Longest Run length of K : 3

Time complexity: O(n), where n is the length of the input string test_str. This is because itertools.groupby() iterates over each character in test_str exactly once, and appending to a list and finding the maximum value in the list take constant time.

Auxiliary Space: O(k), where k is the number of runs of the character K in test_str. This is because the list counts contains one element for each run of K, and each element takes up constant space. Therefore, the space used by the algorithm is proportional to the number of runs of K in the input string, rather than the length of the input string itself.

Method #6: Using Counter from collections module:

Algorithm:

1.Create a Counter object from the input string using collections.Counter() function.
2.Find the count of the given character in the Counter object using the get() method.
3.Return the count as the result.

Python3
from collections import Counter  test_str = 'geeksforgeeeeeks' K = 'e' # printing original string print("The original string is : " + test_str)   count_dict = Counter(test_str) longest_run = 0 curr_run = 0 for char in test_str:     if char == K:         curr_run += 1         longest_run = max(longest_run, curr_run)     else:         curr_run = 0  print("Longest Run length of K : " + str(longest_run)) # This code is contributed by Jyothi pinjala 

Output
The original string is : geeksforgeeeeeks Longest Run length of K : 5

Time Complexity: O(n) (where n is the length of the input string)
The time complexity is dominated by the creation of the Counter object, which takes O(n) time.

Space Complexity: O(k) (where k is the number of unique characters in the input string)
The space complexity is dominated by the space required to store the Counter object, which takes O(k) space.

Method #7: Using regex

Import the re module.
Define a regular expression pattern that matches consecutive occurrences of the target character. For instance, the pattern for the character 'e' would be r'e+'.
Use the re.findall() method to find all non-overlapping matches of the pattern in the input string.
Compute the length of each match and return the maximum length.

Python3
import re  def longest_run_regex(string, k):     pattern = r'{}+'.format(k)     matches = re.findall(pattern, string)     return max(len(match) for match in matches)  test_str = 'geeksforgeeeeeks' k = 'e'  longest_run = longest_run_regex(test_str, k) print("Longest Run length of K : " + str(longest_run)) 

Output
Longest Run length of K : 5 

The time complexity  O(n^2), where n is the length of the string. 
The space complexity O(n^2), where n is the length of the string. 


Next Article
Python | Longest Run of given Character in String

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

    Get Last N characters of a string - Python
    We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python.Using String Slicing String slicing is the fastest and most straigh
    2 min read
    Python | Extract length of longest string in list
    Sometimes, while working with a lot of data, we can have a problem in which we need to extract the maximum length of all the strings in list. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using max() + generator
    4 min read
    Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach.Using for loopThe simplest way to iterate over the characters in
    2 min read
    Python - Longest Substring Length of K
    Given a String and a character K, find longest substring length of K. Input : test_str = 'abcaaaacbbaa', K = b Output : 2 Explanation : b occurs twice, 2 > 1. Input : test_str = 'abcaacccbbaa', K = c Output : 3 Explanation : Maximum times c occurs is 3. Method #1: Using loop This is brute way to
    7 min read
    Find Length of String in Python
    In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop.
    2 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