Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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 | Union Operation in two Strings
Next article icon

Python | Union Operation in two Strings

Last Updated : 16 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

One of the string operation can be computing the union of two strings. This can be useful application that can be dealt with. This article deals with computing the same through different ways. 

Method 1 : Naive Method The task of performing string union can be computed by naive method by creating an empty string and checking for new occurrence of character common to both string and not common strings and appending it and hence computing the new union string. This can be achieved by loops and if/else statements. 

Python3
# Python 3 code to demonstrate  # Union Operation in two Strings # using naive method   # initializing strings test_str1 = 'GeeksforGeeks' test_str2 = 'Codefreaks'  # Printing initial strings print ("The original string 1 is : " + test_str1) print ("The original string 2 is : " + test_str2)  # using naive method to # Union Operation in two Strings res = "" temp = test_str1 for i in test_str2:     if i not in temp:         test_str1 += i          # printing result print ("The string union is : " + test_str1) 
Output : 
The original string 1 is : GeeksforGeeks The original string 2 is : Codefreaks The string union is : GeeksforGeeksCda

Time Complexity: O(n*n), where n is the number of elements in the “test_str”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_str”.

  Method 2 : Using set() + union() Set in python usually can perform the task of performing set operations such as set union. This utility of sets can be used to perform this task as well. Firstly, both the strings are converted into sets using set() and then union is performed using union(). Returns the sorted set. 

Python3
# Python 3 code to demonstrate  # Union Operation in two Strings # using set() + union()  # initializing strings test_str1 = 'GeeksforGeeks' test_str2 = 'Codefreaks'  # Printing initial strings print ("The original string 1 is : " + test_str1) print ("The original string 2 is : " + test_str2)  # using set() + union() to # Union Operation in two Strings res = set(test_str1).union(test_str2)          # printing result print ("The string union is : " + str(res)) 
Output : 
The original string 1 is : GeeksforGeeks The original string 2 is : Codefreaks The string union is : {'s', 'G', 'r', 'e', 'o', 'f', 'k', 'C', 'd', 'a'}

Method 3 : Using set() + | Another approach to perform the union operation on two strings could be using the | operator. The | operator returns a set that contains all elements from the first set and all elements from the second set that are not present in the first set.

Here is an example implementation:

Python3
# Python 3 code to demonstrate  # Union Operation in two Strings # using | operator     # initializing strings test_str1 = 'GeeksforGeeks' test_str2 = 'Codefreaks'    # Printing initial strings print ("The original string 1 is : " + test_str1) print ("The original string 2 is : " + test_str2)    # using | operator to perform union res = set(test_str1) | set(test_str2)            # printing result print ("The string union is : " ,res) 

Output
The original string 1 is : GeeksforGeeks The original string 2 is : Codefreaks The string union is :  {'r', 'a', 'k', 'o', 's', 'G', 'd', 'e', 'C', 'f'}

The time complexity of this approach would be O(len(test_str1) + len(test_str2)) since we need to create sets from both strings and then perform the union operation on them. The space complexity would be O(len(res)) as the size of the result set would be equal to the number of unique characters in the union of the two strings.

Method 4 : Using reduce

In this method we first import the reduce function from functools. Then, we initialize two strings test_str1 and test_str2. We print the initial strings and then use reduce to perform the union operation. In the lambda function, we check if the character c is already present in the accumulated string acc. If it is not present, we append it to the accumulated string, otherwise we just return the accumulated string. We provide the initial accumulated string as test_str1 and the iterable as test_str2. Finally, we print the result of the union operation.

Python3
# Python3 code to demonstrate # Union Operation in two Strings # using reduce  from functools import reduce  # Initializing strings test_str1 = 'GeeksforGeeks' test_str2 = 'Codefreaks'  # Printing initial strings print("The original string 1 is : " + test_str1) print("The original string 2 is : " + test_str2)  # Using reduce to perform Union Operation on two strings res = reduce(lambda acc, c: acc + c if c not in acc else acc, test_str2, test_str1)  # Printing the result print("The string union is : " + res) 

Output
The original string 1 is : GeeksforGeeks The original string 2 is : Codefreaks The string union is : GeeksforGeeksCda 

Time Complexity: O(n*n), where n is the length of the concatenated string. 
Auxiliary Space: O(n), where n is the number of elements in the “test_str”.


Next Article
Python | Union Operation in two Strings

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

    Convert tuple to string in Python
    The goal is to convert the elements of a tuple into a single string, with each element joined by a specific separator, such as a space or no separator at all. For example, in the tuple ('Learn', 'Python', 'Programming'), we aim to convert it into the string "Learn Python Programming". Let's explore
    2 min read
    Python - Combine Strings to Matrix
    Sometimes while working with data, we can receive separate data in the form of strings and we need to compile them into Matrix for its further use. This can have applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split
    4 min read
    How to Append to String in Python ?
    In Python, Strings are immutable datatypes. So, appending to a string is nothing but string concatenation which means adding a string at the end of another string.Let us explore how we can append to a String with a simple example in Python.Pythons = "Geeks" + "ForGeeks" print(s)OutputGeeksForGeeks N
    2 min read
    Convert String to Tuple - Python
    When we want to break down a string into its individual characters and store each character as an element in a tuple, we can use the tuple() function directly on the string. Strings in Python are iterable, which means that when we pass a string to the tuple() function, it iterates over each characte
    2 min read
    Python | Add one string to another
    The concatenation of two strings has been discussed multiple times in various languages. But the task is how to add to a string in Python or append one string to another in Python. Example Input: 'GFG' + 'is best' Output: 'GFG is best' Explanation: Here we can add two string using "+" operator in Py
    5 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