Python – Longest Substring Length of K
Last Updated :
16 May, 2023
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
test_str = 'abcaaaacbbaa'
print ( "The original string is : " + str (test_str))
K = 'a'
cnt = 0
res = 0
for idx in range ( len (test_str)):
if test_str[idx] = = K:
cnt + = 1
else :
cnt = 0
res = max (res, cnt)
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
import re
test_str = 'abcaaaacbbaa'
print ( "The original string is : " + str (test_str))
K = 'a'
res = re.findall(r' ' + K + ' + ', test_str)
res = len ( max (res, key = len ))
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:
- Use itertools.groupby() to group characters in test_str by their values
- Filter out the groups where the character is not equal to K
- Generate a list of lengths of all remaining groups using list comprehension
- Return the maximum value in the list using max()
Python3
import itertools
test_str = 'abcaaaacbbaa'
K = 'a'
print ( "The original string is : " + str (test_str))
res = max ([ len ( list (grp)) for char, grp in itertools.groupby(test_str) if char = = K])
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
test_str = 'abcaaaacbbaa'
print ( "The original string is : " + str (test_str))
K = 'a'
res = max ( len (sub_str) for sub_str in re.split(f '[^{K}]' , test_str))
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
import re
test_str = 'abcaaaacbbaa'
print ( "The original string is : " + str (test_str))
K = 'a'
matches = re.findall(K + '+' , test_str)
res = len ( max (matches, key = len ))
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
test_str = 'abcaaaacbbaa'
K = 'a'
arr = np.array( list (test_str))
indices = np.where(arr = = K)[ 0 ]
differences = np.diff(indices)
res = np. max (differences)
print ( "The original string is : " + str (test_str))
print ( "The Longest Substring Length : " + str (res))
|
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
test_str = 'abcaaaacbbaa'
print ( "The original string is : " + str (test_str))
K = 'a'
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)
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
Longest String in list - Python
We are given a list of strings, and our task is to find the longest string present in the list. If there are multiple strings with the maximum length, we should return the first one that appears. For example, given a = ["alpha", "gamma", "epsilon", "delta"], the longest string is "epsilon". Let's di
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
Python - Extract K length substrings
The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in Python Using List Comprehension List comprehension is
3 min read
Python | Longest Run of given Character in String
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
6 min read
How to Get Index of a Substring in Python?
To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Letâs explore how to efficiently get the index of a substring. The simplest way to get
2 min read
Python - Get all substrings of given string
A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach. Using List Comprehension :List comprehension offers a concise way to create lists by applying an expression to each element
3 min read
Python - Maximum String value length of Key
The task of finding the maximum string length of a specific key in a list of dictionaries involves identifying the longest string associated with the given key. Given a list of dictionaries, the goal is to extract the string values of the specified key, compute their lengths and determine the maximu
3 min read
Python - Words Lengths in String
We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6]. Using Lis
2 min read
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python. Using str.find() The find() method searches for the first occurrence of the specified substring and retur
3 min read
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 straig
2 min read