Given a string and a character, insert a character after every K occurrence.
Input : test_str = ‘GeeksforGeeks’, K = 2, add_chr = “;”
Output : [‘;GeeksforGeeks’, ‘Ge;eksforGeeks’, ‘Geek;sforGeeks’, ‘Geeksf;orGeeks’, ‘Geeksfor;Geeks’, ‘GeeksforGe;eks’, ‘GeeksforGeek;s’]
Explanation : All combinations after adding ; after every K elements.
Input : test_str = ‘GeeksforGeeks’, K = 2, add_chr = “*”
Output : [‘*GeeksforGeeks’, ‘Ge*eksforGeeks’, ‘Geek*sforGeeks’, ‘Geeksf*orGeeks’, ‘Geeksfor*Geeks’, ‘GeeksforGe*eks’, ‘GeeksforGeek*s’]
Explanation : All combinations after adding * after every K elements.
Method 1: Using loop + slicing
This is one of the ways in which this task can be performed. In this, we slice string on every Kth occurrence using string slicing and append characters between them.
Python3
def insertCharacterAfterKelements(test_str, K, char):
res = []
for idx in range ( 0 , len (test_str), K):
res.append(test_str[:idx] + char + test_str[idx:])
return str (res)
input_str = 'GeeksforGeeks'
print ( "The original string is : " + str (input_str))
K = 2
add_chr = ";"
print ( "The extracted strings : " +
insertCharacterAfterKelements(input_str, K, add_chr))
|
OutputThe original string is : GeeksforGeeks
The extracted strings : [';GeeksforGeeks', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using (list comprehension + slicing)
This is yet another way in which this task can be performed. In this, we perform a similar task as loop difference being that list comprehension is employed as shorthand to solve this question.
Python3
def insertCharacterAfterKelements(test_str, K, char):
res = [test_str[:idx] + char + test_str[idx:]
for idx in range ( 0 , len (test_str), K)]
return str (res)
input_str = 'GeeksforGeeks'
print ( "The original string is : " + str (input_str))
K = 2
add_chr = ";"
print ( "The extracted strings : " +
insertCharacterAfterKelements(input_str, K, add_chr))
|
OutputThe original string is : GeeksforGeeks
The extracted strings : [';GeeksforGeeks', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s']
Time Complexity: O(n)
Auxiliary Space: O(n)