Given a string and a character, insert a character after every K occurrence.
Input : test_str = ‘neveropen’, K = 2, add_chr = “;”
Output : [‘;neveropen’, ‘Ge;eksforGeeks’, ‘Geek;sforGeeks’, ‘Geeksf;orGeeks’, ‘Geeksfor;Geeks’, ‘GeeksforGe;eks’, ‘GeeksforGeek;s’]
Explanation : All combinations after adding ; after every K elements.Input : test_str = ‘neveropen’, K = 2, add_chr = “*”
Output : [‘*neveropen’, ‘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
# Python3 code to demonstrate working of # Insert character after every K elements # Using loop + string slicing # Function to Insert character # in each duplicate string # after every K elements def insertCharacterAfterKelements(test_str, K, char): res = [] # using loop to iterate for idx in range ( 0 , len (test_str), K): # appending all the results res.append(test_str[:idx] + char + test_str[idx:]) return str (res) # Driver Code # initializing string input_str = 'neveropen' # printing original string print ( "The original string is : " + str (input_str)) # initializing K K = 2 # initializing add char add_chr = ";" # printing result print ( "The extracted strings : " + insertCharacterAfterKelements(input_str, K, add_chr)) |
The original string is :neveropen The extracted strings : [';neveropen', '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
# Python3 code to demonstrate working of # Insert character after every K elements # Using list comprehension + string slicing # Function to Insert character # in each duplicate string # after every K elements def insertCharacterAfterKelements(test_str, K, char): # list comprehension to bind logic in one. res = [test_str[:idx] + char + test_str[idx:] for idx in range ( 0 , len (test_str), K)] return str (res) # Driver Code # initializing string input_str = 'neveropen' # printing original string print ( "The original string is : " + str (input_str)) # initializing K K = 2 # initializing add char add_chr = ";" # printing result print ( "The extracted strings : " + insertCharacterAfterKelements(input_str, K, add_chr)) |
The original string is :neveropen The extracted strings : [';neveropen', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s']
Time Complexity: O(n)
Auxiliary Space: O(n)