Sometimes, while working with Python strings, we can have a problem in which we need to perform replace of characters after certain repetitions of characters. This can have applications in many domains including day-day and competitive programming.
Method #1: Using loop + string slicing
This is brute force way in which this problem can be solved. In this, we run a loop on a string and keep track of occurrences and perform replace when above K occurrence.
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
K = 2
repl_char = "*"
for sub in set (test_str):
for idx in [idx for idx in range ( len (test_str)) if test_str[idx] = = sub][K:]:
test_str = test_str[:idx] + repl_char + test_str[idx + 1 :]
print ( "The string after performing replace : " + test_str)
|
Output :
The original string is : geeksforgeeks is best for geeks
The string after performing replace : geeksforg**ks i* b**t*for******
Time Complexity: O(n2), where n is the length of the string.
Auxiliary Space: O(n), where n is the length of the string.
Method #2 : Using join() + count() + enumerate()
This is the shorthand by which this task can be performed. In this, we employ count() to check for the count of strings and join() and enumerate() can be used to perform the task of new string construction.
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
K = 2
repl_char = "*"
res = "".join( chr if test_str.count( chr , 0 , idx) < K
else repl_char for idx, chr in enumerate (test_str))
print ( "The string after performing replace : " + res)
|
Output :
The original string is : geeksforgeeks is best for geeks
The string after performing replace : geeksforg**ks i* b**t*for******
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 3: Using list comprehension:
- Create a list of characters using a list comprehension, where each character is replaced with repl_char if its count.
- The first ‘i’th characters of the string are greater than or equal to K. The enumerate function is used to get the index i of each character.
- Finally, the list is joined back into a string using the join method.
Python3
test_str = "geeksforgeeks is best for geeks"
K = 2
repl_char = "*"
chars =
res = "".join(chars)
print ( "The string after performing replace : " + res)
|
Output
The string after performing replace : geeksforg**ks i* b**t*for******
Time complexity: O(n^2), where n is the length of the input string, because test_str.count is called n times, each time with a string of length up to n. The Auxiliary space: O(n), because a new list of length n is created
Method 4: Using list and slicing
Approach:
- Convert the input string test_str to a list of characters using the list() method.
Initialize a counter variable to keep track of the number of occurrences of each character in the input string.
- Loop through each character in the list.
- If the number of occurrences of the current character is less than K, then do nothing.
- If the number of occurrences of the current character is equal to K, then replace all subsequent occurrences of the current character with the replacement character repl_char.
- If the number of occurrences of the current character is greater than K, then replace the current occurrence of the character with the replacement character repl_char.
- Increment the counter for the current character.
- Convert the list back to a string using the join() method.
- Print the modified string.
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
K = 2
repl_char = "*"
lst = list (test_str)
counter = {}
for i, char in enumerate (lst):
if char not in counter:
counter[char] = 0
if counter[char] = = K:
for j in range (i, len (lst)):
if lst[j] = = char:
lst[j] = repl_char
elif counter[char] > K:
lst[i] = repl_char
counter[char] + = 1
res = ''.join(lst)
print ( "The string after performing replace : " + res)
|
Output
The original string is : geeksforgeeks is best for geeks
The string after performing replace : geeksforg**ks i* b**t*for******
Time complexity: O(n^2), where n is the length of the input string.
Auxiliary space: O(k), where k is the number of unique characters in the input string.
Method 5: Using a dictionary
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is: " + test_str)
K = 2
repl_char = "*"
counter = {}
res = ""
for char in test_str:
if char not in counter:
counter[char] = 1
else :
counter[char] + = 1
if counter[char] < = K:
res + = char
else :
res + = repl_char
print ( "The string after performing replace: " + res)
|
Output
The original string is: geeksforgeeks is best for geeks
The string after performing replace: geeksforg**ks i* b**t*for******
Time Complexity: O(n), where n is the length of the input string. It iterates through the string once and performs constant-time operations for each character.
Auxiliary Space: O(n), where n is the length of the input string.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 May, 2023
Like Article
Save Article