Open In App

Python | Consecutive prefix overlap concatenation

Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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)


Output

The 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.



Last Updated : 16 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads