Open In App

Python – K length consecutive characters

Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, extract all the K-length consecutive characters.

Input : test_str = ‘geekforgeeeksss is bbbest forrr geeks’, K = 3 
Output : [‘eee’, ‘sss’, ‘bbb’, ‘rrr’] 
Explanation : K length consecutive strings extracted. 

Input : test_str = ‘geekforgeeeksss is bbbest forrrr geeks’, K = 4 
Output : [‘rrrr’] 
Explanation : K length consecutive strings extracted.

Method #1: Using loop

In this, we maintain a counter to check for elements consecution, if they are exactly equal to K before separate element, then the number, appending by itself K times is returned.

Python3




# Python3 code to demonstrate working of
# K length consecutive characters
# Using loop
 
# initializing string
test_str = 'geekforgeeekssss is bbbbest forrrr geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 4
 
res = []
curr, cnt = None, 0
for chr in test_str:
     
    # increment for similar character
    if chr == curr:
        cnt += 1
    else:
        curr, cnt = chr, 1
         
    # if count exactly K, element is added
    if cnt == K:
        res.append(K * chr)
     
# printing result
print("The K length similar characters : " + str(res))


Output

The original string is : geekforgeeekssss is bbbbest forrrrrrr geeks
The K length similar characters : ['ssss', 'bbbb', 'rrrr']

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

Method #2 : Using split() + enumerate()

In this, we create a substring from each index, and if each element of those substrings are equal, then it is returned to the result.

Python3




# Python3 code to demonstrate working of
# K length consecutive characters
# Using split() + enumerate()
 
# initializing string
test_str = 'geekforgeeekssss is bbbbest forrrr geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 4
 
res = []
for idx, ele in enumerate(test_str):
     
    # creating equi string
    substr = ele * K
     
    # checking if equal to actual string
    if test_str[idx : idx + K] == substr:
        res.append(substr)
     
# printing result
print("The K length similar characters : " + str(list(set(res))))


Output

The original string is : geekforgeeekssss is bbbbest forrrrrrr geeks
The K length similar characters : ['bbbb', 'ssss', 'rrrr']

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

Method 3 : use the sliding window technique 

Step-by-step approach:

  1. Initialize two pointers, start and end, both pointing to the first character of the string.
  2. Create a dictionary to store the frequency of characters in the current window.
  3. Move the end pointer to the right until the length of the current window is equal to K.
  4. Check if all the characters in the current window are the same by comparing the length of the dictionary with 1. If yes, add the current substring to the result list.
  5. Move the start pointer to the right and update the frequency dictionary accordingly.
  6. Repeat steps 3-5 until the end pointer reaches the end of the string.
  7. Remove duplicates from the resulting list using set() function.
  8. Print the list of K length similar characters.

Python3




# initializing string
test_str = 'geekforgeeekssss is bbbbest forrrr geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 4
 
# initialize pointers and dictionary
start = 0
end = 0
freq = {}
 
# initialize result list
res = []
 
while end < len(test_str):
    # expand window
    if test_str[end] in freq:
        freq[test_str[end]] += 1
    else:
        freq[test_str[end]] = 1
    end += 1
     
    # shrink window if necessary
    if end - start == K:
        if len(freq) == 1:
            res.append(test_str[start:end])
        if freq[test_str[start]] == 1:
            del freq[test_str[start]]
        else:
            freq[test_str[start]] -= 1
        start += 1
 
# removing duplicates
res = list(set(res))
 
# printing result
print("The K length similar characters : " + str(res))


Output

The original string is : geekforgeeekssss is bbbbest forrrr geeks
The K length similar characters : ['ssss', 'bbbb', 'rrrr']

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(K), where K is the length of the substring we are looking for.



Last Updated : 03 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads