Python | Consecutive prefix overlap concatenation
Last Updated :
16 May, 2023
Sometimes, while working with Python Strings, we can have application in which we need to perform the concatenation of all elements in String list. This can be tricky in cases we need to overlap suffix of current element with prefix of next in case of a match. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + endswith() + join() + list comprehension + zip() The combination of above functions can be used to perform this task. In this, we use loop for the logic of join/no join using endswith(). If a join, that is performed using join(). Whole logic is compiled in list comprehension.
Python3
# Python3 code to demonstrate working of
# Consecutive prefix overlap concatenation
# Using endswith() + join() + list comprehension + zip() + loop
def help_fnc(i, j):
for ele in range(len(j), -1, -1):
if i.endswith(j[:ele]):
return j[ele:]
# initializing list
test_list = ["gfgo", "gone", "new", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Consecutive prefix overlap concatenation
# Using endswith() + join() + list comprehension + zip() + loop
res = ''.join(help_fnc(i, j) for i, j in zip([''] +
test_list, test_list))
# printing result
print("The resultant joined string : " + str(res))
Output : The original list is : ['gfgo', 'gone', 'new', 'best']
The resultant joined string : gfgonewbest
Time Complexity: O(n*n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
Method #2 : Using reduce() + lambda + next() The combination of above methods can also be employed to solve this problem. In this, we perform the task of performing overlap using next() and endswith, and rest of task is performed using reduce() and lambda.
Python3
# Python3 code to demonstrate working of
# Consecutive prefix overlap concatenation
# Using reduce() + lambda + next()
# initializing list
test_list = ["gfgo", "gone", "new", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Consecutive prefix overlap concatenation
# Using reduce() + lambda + next()
res = reduce(lambda i, j: i + j[next(idx
for idx in reversed(range(len(j) + 1))
if i.endswith(j[:idx])):], test_list, '', )
# printing result
print("The resultant joined string : " + str(res))
Output : The original list is : ['gfgo', 'gone', 'new', 'best']
The resultant joined string : gfgonewbest
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the reduce() + lambda + next() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method 3 : Using a while loop and string slicing:
Python3
# initializing list
test_list = ["gfgo", "gone", "new", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Consecutive prefix overlap concatenation using a while loop and string slicing
res = test_list[0]
i = 1
while i < len(test_list):
for j in range(len(test_list[i]), -1, -1):
if test_list[i-1].endswith(test_list[i][:j]):
res += test_list[i][j:]
break
i += 1
# printing result
print("The resultant joined string : " + str(res))
OutputThe original list is : ['gfgo', 'gone', 'new', 'best']
The resultant joined string : gfgonewbest
Time complexity: O(n^2) (in the worst case when all strings have the same prefix)
Auxiliary space: O(n) (in the worst case when there are no overlapping prefixes
Method #4: Using recursion
- Define a recursive function "concat_strings" that takes two input strings and returns their overlapping concatenation.
- Base case: if one of the strings is empty, return the other string.
- Recursive case: find the length of the longest overlapping prefix between the two strings.
- Concatenate the two strings after the overlapping prefix using string slicing.
- Recursively call the "concat_strings" function with the remaining parts of the two strings.
- Call the "concat_strings" function with the first two strings in the list to get the final concatenated string.
Python3
# Python3 code to demonstrate working of
# Consecutive prefix overlap concatenation
# Using recursion
# initializing list
test_list = ["gfgo", "gone", "new", "best"]
# printing original list
print("The original list is : " + str(test_list))
# recursive function to concatenate two strings with overlapping prefix
def concat_strings(str1, str2):
if len(str1) == 0 or len(str2) == 0:
return str1 + str2
for i in range(min(len(str1), len(str2)), 0, -1):
if str1.endswith(str2[:i]):
return str1 + str2[i:]
return str1 + str2
# Consecutive prefix overlap concatenation
# Using recursion
result = test_list[0]
for i in range(1, len(test_list)):
result = concat_strings(result, test_list[i])
# printing result
print("The resultant joined string : " + result)
OutputThe original list is : ['gfgo', 'gone', 'new', 'best']
The resultant joined string : gfgonewbest
Time complexity: O(n^2) where n is the length of the longest string in the list.
Auxiliary space: O(n) for the recursive call stack.
Similar Reads
Python - Concatenate consecutive elements in Tuple Sometimes, while working with data, we can have a problem in which we need to find cumulative results. This can be of any type, product, or summation. Here we are gonna discuss adjacent element concatenation. Letâs discuss certain ways in which this task can be performed. Method #1 : Using zip() + g
4 min read
Python - Length Conditional Concatenation Given a list of strings, perform concatenation of Strings whose length is greater than K. Input : test_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything'], K = 3Output : BestEverything Explanation : All elements with Length > 3 are concatenated. Input : test_list = ["Gfg", 'is', "Best", 'for'
4 min read
Python | Concatenate N consecutive elements in String list Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let's discuss certain ways in which this task can be performed. Method #1: Using format() + zip() + i
8 min read
Python | Custom Consecutive Character Pairing Sometimes, while working with Python Strings, we can have problem in which we need to perform the pairing of consecutive strings with deliminator. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + list comprehension T
4 min read
Python - Consecutive Alphabetic Occurrence Sometimes, while working with Strings, we can have a problem in which we need to check whether we can find occurrence of characters consecutive and according to English alphabets. This kind of problem can occur in school programming and day-day programming. Lets discuss certain ways in which this ta
4 min read
Python - Conditional Prefix in List Given a list of elements, attach different prefix according to condition. Input : test_list = [45, 53, 76, 86, 3, 49], pref_1 = "LOSE-", pref_2 = "WIN-" Output : ['LOSE-45', 'WIN-53', 'WIN-76', 'WIN-86', 'LOSE-3', 'LOSE-49'] Explanation : All 50+ are prefixed as "WIN-" and others as "LOSE-". Input :
8 min read
Python - String Matrix Concatenation Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
4 min read
Python - Horizontal Concatenation of Multiline Strings Horizontal concatenation of multiline strings involves merging corresponding lines from multiple strings side by side using methods like splitlines() and zip(). Tools like itertools.zip_longest() help handle unequal lengths by filling missing values, and list comprehensions format the result.Using z
3 min read
Python | Consecutive String Comparison Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it's next element in a list and return all strings whose next element is similar list. Let's discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop
3 min read