Open In App

Python – Longest Substring Length of K

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 solve this problem, in this, when K is encountered, counter is maintained till other character occurs, and count is noted, the maximum of these counts is kept and is returned as result.

Python3




# Python3 code to demonstrate working of
# Longest Substring of K
# Using loop
 
# initializing string
test_str = 'abcaaaacbbaa'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing K
K = 'a'
 
cnt = 0
res = 0
for idx in range(len(test_str)):
     
    # increment counter on checking
    if test_str[idx] == K:
        cnt += 1
    else:
        cnt = 0
         
    # retaining max
    res = max(res, cnt)
 
# printing result
print("The Longest Substring Length : " + str(res))


Output

The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Method #2: Using findall() + max()

In this, we get all the possible substrings of K using findall() and max() is used over it to get maximum length with len as key.

Python3




# Python3 code to demonstrate working of
# Longest Substring of K
# Using findall() + max()
import re
 
# initializing string
test_str = 'abcaaaacbbaa'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing K
K = 'a'
 
# getting all substrings
res = re.findall(r'' + K + '+', test_str)
 
# getting maximum of substrings Length
res = len(max(res, key = len))
 
# printing result
print("The Longest Substring Length : " + str(res))


Output

The original string is : abcaaaacbbaa
The Longest Substring Length : 4

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

Method #3:  Using itertools.groupby

Step-by-step Algorithm:

  1. Use itertools.groupby() to group characters in test_str by their values
  2. Filter out the groups where the character is not equal to K
  3. Generate a list of lengths of all remaining groups using list comprehension
  4. Return the maximum value in the list using max()

Python3




# Importing itertools module
import itertools
 
# Initializing input string and the character to be searched
test_str = 'abcaaaacbbaa'
K = 'a'
 
# printing the original string
print("The original string is : " + str(test_str))
 
# Using groupby() function to group the characters of the string
res = max([len(list(grp)) for char, grp in itertools.groupby(test_str) if char == K])
 
# Printing the result
print("The Longest Substring Length : " + str(res))


Output

The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Time complexity: O(n) where n is the length of the input string test_str
Space complexity: O(1)

Method #4: Using generator expression, max() and re.split() function

  • Importing the re module
  • The test_str variable is initialized with the given string.
  • re.split() is used to split the string by every character except K, using a regular expression.
  • A generator expression is used to get the length of each substring generated by re.split().
  • max() function is used to get the maximum length of the substrings.
  • Printing the result.

Python3




import re
 
# initializing string
test_str = 'abcaaaacbbaa'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing K
K = 'a'
 
# Using generator expression, max() and re.split() function
res = max(len(sub_str) for sub_str in re.split(f'[^{K}]', test_str))
 
# printing result
print("The Longest Substring Length : " + str(res))


Output

The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Time complexity: O(n) where n is the length of the input string test_str
Space complexity: O(n) where n is the length of the input string test_str

Method 5: Using Regular expression and max()

  • Import the re module which provides support for regular expressions.
  • Define the input string and the character to be searched for.
  • Use re.findall() method to find all the occurrences of the character in the string.
  • Use the max() function to find the longest substring of the character by comparing the lengths of all the substrings obtained from step 3.
  • Print the length of the longest substring obtained in step 4.

Python3




# Python3 code to demonstrate working of
# Longest Substring of K
# Using Regular expression and max()
 
# importing regular expression module
import re
 
# initializing string
test_str = 'abcaaaacbbaa'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing K
K = 'a'
 
# find all occurrences of the character
matches = re.findall(K + '+', test_str)
 
# find the length of the longest substring
res = len(max(matches, key=len))
 
# printing result
print("The Longest Substring Length : " + str(res))


Output

The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Time complexity: O(n) where n is the length of the input string, as we need to traverse the string only once.
Auxiliary space: O(n) for storing the matches found using re.findall().

Method 6: Using numpy:

Step-by-step approach:

  • Create a numpy array from the input string.
  • Use the np.where() function to find the indices where the character K appears in the array.
  • Use the np.diff() function to calculate the consecutive differences between the indices found in step 2.
  • Use the np.max() function to find the maximum consecutive difference, which gives the length of the longest
  • substring of the character K.
  • Return the result.

Python3




import numpy as np
 
# Initializing input string and the character to be searched
test_str = 'abcaaaacbbaa'
K = 'a'
 
# creating a numpy array from the input string
arr = np.array(list(test_str))
 
# finding the indices where the character K appears
indices = np.where(arr == K)[0]
 
# finding the consecutive differences between indices
differences = np.diff(indices)
 
# finding the maximum consecutive difference
res = np.max(differences)
 
# printing the original string and the result
print("The original string is : " + str(test_str))
print("The Longest Substring Length : " + str(res))
#This code is contributed by Rayudu.


Output:
The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Time Complexity:

Creating a numpy array from the input string takes O(n) time, where n is the length of the input string.
The np.where() function takes O(n) time to find the indices where the character K appears in the array.
The np.diff() function takes O(m) time, where m is the number of indices where the character K appears in the array.
The np.max() function takes O(m) time to find the maximum consecutive difference.
Therefore, the overall time complexity of the algorithm is O(n + m).

Auxiliary Space:

Creating a numpy array from the input string takes O(n) space, where n is the length of the input string.
The np.where() function returns an array of size m, where m is the number of indices where the character K appears in the array.
The np.diff() function creates a new array of size m-1.
Therefore, the overall space complexity of the algorithm is O(n + m).

Method #7: Using dynamic programming

Step-by-step approach:

  • Initialize a 1D array dp of length n, where dp[i] represents the length of the longest substring of the input string that ends at index i.
  • Initialize dp[0] to 1 if the first character of the input string is ‘a’, otherwise set it to 0.
  • Iterate over the characters in the input string starting from index 1. If the current character is equal to the target character ‘a’, set dp[i] to dp[i-1] + 1. Otherwise, set dp[i] to 0.
  • Keep track of the maximum value in the dp array.
  • Return the maximum value in the dp array as the length of the longest substring.

Python3




# initializing string
test_str = 'abcaaaacbbaa'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing K
K = 'a'
 
# Using dynamic programming
n = len(test_str)
dp = [0] * n
dp[0] = 1 if test_str[0] == K else 0
for i in range(1, n):
    if test_str[i] == K:
        dp[i] = dp[i-1] + 1
    else:
        dp[i] = 0
max_count = max(dp)
 
# printing result
print("The Longest Substring Length : " + str(max_count))


Output

The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are using a 1D array dp of length n to store the lengths of the longest substrings ending at each index of the input string.



Similar Reads

Python Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7 The desired time complexi
6 min read
Length of the longest substring with consecutive characters
Given string str of lowercase alphabets, the task is to find the length of the longest substring of characters in alphabetical order i.e. string "dfabck" will return 3. Note that the alphabetical order here is considered circular i.e. a, b, c, d, e, ..., x, y, z, a, b, c, .... Examples: Input: str = "abcabcdefabc" Output: 6 All valid sub-strings ar
7 min read
Length of the longest substring that contains even number of vowels
Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring consisting of each vowel an even number of times Examples: Input: S= "bcbcbc"Output: 6Explanation:Consider the substring S[0, 5] i.e., "bcbcbc" is the longest substring because all vowels: a, e, i, o and u appear 0(which is even) number of
8 min read
SequenceMatcher in Python for Longest Common Substring
Given two strings ‘X’ and ‘Y’, print the longest common sub-string. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx" Output : abcdez We have existing solution for this problem please refer Print the longest common substring link. We will solve problem in python using SequenceMatcher.find
2 min read
Python | Find longest consecutive letter and digit substring
Given a String (may contain both letters and digits), write a Python program to find the longest consecutive letter and digit substring. Examples: Input : geeks123available Output : ('available', 123) Input : 98apple658pine Output : ('apple', 658) Approach #1 : Brute force This is the Naive or brute force approach to find the longest consecutive le
5 min read
Python Map | Length of the Longest Consecutive 1's in Binary Representation of a given integer
Given a number n, find length of the longest consecutive 1s in its binary representation. Examples: Input : n = 14 Output : 3 The binary representation of 14 is 1110. Input : n = 222 Output : 4 The binary representation of 222 is 11011110. We have existing solution for this problem please refer Length of the Longest Consecutive 1s in Binary Represe
3 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 expression, The combination of above functionalit
4 min read
Python Program to Return the Length of the Longest Word from the List of Words
The problem is to go through all the words in an array and the program should return the word with the longest one. Consider for example we are having an array, and we have numbers in alphabetic form, now when we pass this array as an input then we should get the word with the longest one. Below I had explained it with an example in order to give a
5 min read
Python Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4 Recommended: Please sol
3 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: C/C++ Code string = "Geeksforgeeks" print(len(string)) Output13String len() Syntax len(string) Parameter String: string of which you want to find the length. Return: It returns
3 min read
Practice Tags :