Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Custom Consecutive Character Pairing
Next article icon

Python | Consecutive prefix overlap concatenation

Last Updated : 16 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
Python | Custom Consecutive Character Pairing
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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 - Vertical Concatenation in Matrix
    Given a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths. Input : [["Gfg", "good"], ["is", "for"]] Output : ['Gfgis', 'goodfor'] Explanation : Column wise concatenated Strings, "Gfg" concatenated with "is", and so on. Input : [["Gfg", "good", "geeks"], ["i
    3 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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences