# 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 string` `test_str ``=` `"geeksforgeeks is best for geeks"`   `# printing original string` `print``(``"The original string is : "` `+` `test_str)`   `# initializing K` `K ``=` `2`   `# initializing Repl char` `repl_char ``=` `"*"`   `# Replace characters after K occurrences` `# Using loop + string slices` `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``:]`   `# printing result` `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

 `# Python3 code to demonstrate working of` `# Replace characters after K occurrences` `# Using join() + count() + enumerate()`   `# initializing string` `test_str ``=` `"geeksforgeeks is best for geeks"`   `# printing original string` `print``(``"The original string is : "` `+` `test_str)`   `# initializing K` `K ``=` `2`   `# initializing Repl char` `repl_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 result` `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:

1. Create a list of characters using a list comprehension, where each character is replaced with repl_char if its count.
2. 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.
3. Finally, the list is joined back into a string using the join method.

## Python3

 `# Initialzing list and value` `test_str ``=` `"geeksforgeeks is best for geeks"` `K ``=` `2`   `repl_char ``=` `"*"`   `chars ``=` `res ``=` `"".join(chars)`   `# Printing the result` `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:

1. 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.
2. 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.
3. Increment the counter for the current character.
4. Convert the list back to a string using the join() method.
5. Print the modified string.

## Python3

 `# initializing string` `test_str ``=` `"geeksforgeeks is best for geeks"`   `# printing original string` `print``(``"The original string is : "` `+` `test_str)`   `# initializing K` `K ``=` `2`   `# initializing Repl char` `repl_char ``=` `"*"`   `# Replace characters after K occurrences` `# Using list and slicing` `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)`   `# printing result` `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

 `# Initializing string` `test_str ``=` `"geeksforgeeks is best for geeks"`   `# Printing original string` `print``(``"The original string is: "` `+` `test_str)`   `# Initializing K` `K ``=` `2`   `# initializing Repl char` `repl_char ``=` `"*"`   `# Replace characters after K occurrences ` `# using a dictionary` `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`   `# Printing result` `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!

Previous
Next