Python | Replace characters after K occurrences

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
# Python3 code to demonstrate working of# Replace characters after K occurrences# Using loop + string slices# initializing stringtest_str = "zambiatek is best forzambiatek"# printing original stringprint("The original string is : " + test_str)# initializing KK = 2# initializing Repl charrepl_char = "*"# Replace characters after K occurrences# Using loop + string slicesfor 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:]# printing resultprint("The string after performing replace : " + test_str) |
The original string is :zambiatek is best forzambiatek The string after performing replace :zambiatekforg**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
# Python3 code to demonstrate working of# Replace characters after K occurrences# Using join() + count() + enumerate()# initializing stringtest_str = "zambiatek is best forzambiatek"# printing original stringprint("The original string is : " + test_str)# initializing KK = 2# initializing Repl charrepl_char = "*"# Replace characters after K occurrences# Using join() + count() + enumerate()res = "".join(chr if test_str.count(chr, 0, idx) < K else repl_char for idx, chr in enumerate(test_str))# printing resultprint("The string after performing replace : " + res) |
The original string is :zambiatek is best forzambiatek The string after performing replace :zambiatekforg**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
# Initialzing list and valuetest_str = "zambiatek is best forzambiatek"K = 2repl_char = "*"chars = res = "".join(chars)# Printing the resultprint("The string after performing replace : " + res) |
The string after performing replace :zambiatekforg**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
# initializing stringtest_str = "zambiatek is best forzambiatek"# printing original stringprint("The original string is : " + test_str)# initializing KK = 2# initializing Repl charrepl_char = "*"# Replace characters after K occurrences# Using list and slicinglst = 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] += 1res = ''.join(lst)# printing resultprint("The string after performing replace : " + res) |
The original string is :zambiatek is best forzambiatek The string after performing replace :zambiatekforg**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
# Initializing stringtest_str = "zambiatek is best forzambiatek"# Printing original stringprint("The original string is: " + test_str)# Initializing KK = 2# initializing Repl charrepl_char = "*"# Replace characters after K occurrences # using a dictionarycounter = {}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# Printing resultprint("The string after performing replace: " + res) |
The original string is:zambiatek is best forzambiatek The string after performing replace:zambiatekforg**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.



