The Wayback Machine - https://web.archive.org/web/20240905200025/https://www.geeksforgeeks.org/python-intersection-of-two-string/
Open In App

Python | Intersection of two String

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings. There are various ways in Python, through which we can perform the Intersection of two strings. Method #1 : Naive Method Create an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. This can be achieved by loops and if/else statements. 

Python3




# Python3 code to demonstrate
# string intersection
# using naive method
 
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
 
# using naive method to
# get string intersection
res = ""
for i in test_str1:
    if i in test_str2 and not i in res:
        res += i
         
# printing intersection
print ("String intersection is : " + res)


Output :

String intersection is : eksfor

Time Complexity: O(n2)
Auxiliary Space: O(n)

  Method #2 : Using set() + intersection() Firstly, both the strings are converted into sets using set() and then intersection is performed using intersection(). Returns the sorted set. 

Python3




# Python3 code to demonstrate
# string intersection
# using set() + intersection()
 
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
 
# using set() + intersection() to
# get string intersection
res = set(test_str1).intersection(test_str2)
         
# printing intersection
print ("String intersection is : " + str(res))


Output :

String intersection is : {'e', 'f', 's', 'o', 'k', 'r'}

Time Complexity: O(n)
Auxiliary Space: O(n)

  Method #3 : Using join() join() performs the task similar to list comprehension in case of lists. This encapsulates whole intersection logic and joins together each element filtered through the intersection logic into one string, hence computing the intersection. It converts the strings into set and then computed & operation on them. 

Python3




# Python3 code to demonstrate
# string intersection
# using join()
 
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
 
# using join() to
# get string intersection
res = ''.join(sorted(set(test_str1) &
         set(test_str2), key = test_str1.index))
         
# printing intersection
print ("String intersection is : " + str(res))


Output :

String intersection is : eksfor

Time Complexity: O(n.log n)
Auxiliary Space: O(n)

 Method #4 : using filter and lambda function

Python3




test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
 
# using lambda and list comprehension
res = "".join(filter(lambda i: i in test_str2, test_str1))
res = {i for i in res}
# printing intersection
print("String intersection is : " + str(res))
#This code is contributed by Jyothi Pinjala.


Output

String intersection is : {'r', 'f', 'k', 'e', 'o', 's'}

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach#5:using & operator

Algorithm

1.Define a function named string_intersection that takes two strings s1 and s2 as input.
2.Create a set of unique characters from s1 using the set() function.
3.Create another set of unique characters from s2 using the set() function.
4.Find the intersection of these two sets using the & operator, which returns a new set that contains only the elements that are common to both sets.
5.Convert this set into a sorted list using the sorted() function.
6.Join the elements of the sorted list into a single string using the join() function.
7.Return the resulting string as the output of the function.

Python3




def string_intersection(s1, s2):
    intersection = set(s1) & set(s2)
    return ''.join(sorted(intersection))
s1= 'GeeksforGeeks'
s2 = 'Codefreaks'
print(string_intersection(s1, s2))


Output

efkors

Time complexity: O(n log n) – due to the sorted() function
Space complexity: O(n) – where n is the size of the intersection set.



Similar Reads

Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Intersection of two dataframe in Pandas - Python
Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them. Syntax: pd.merge(df1, df2, how) Example 1: import pandas as pd # Creating Data frames df1 = {'A': [1, 2, 3, 4], 'B': ['abc', 'def', 'efg', 'ghi'
1 min read
Python | Intersection of two lists
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. Examples: Input : lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]Output :[
6 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Python set operations (union, intersection, difference and symmetric difference)
This article demonstrates different operations on Python sets. Examples: Input : A = {0, 2, 4, 6, 8} B = {1, 2, 3, 4, 5} Output : Union : [0, 1, 2, 3, 4, 5, 6, 8] Intersection : [2, 4] Difference : [8, 0, 6] Symmetric difference : [0, 1, 3, 5, 6, 8] In Python, below quick operands can be used for different operations. | for union. & for interse
1 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec
2 min read
Python | Pandas TimedeltaIndex.intersection
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.intersection() function return a new Index with elements from the index that are common to both the indexes. This
2 min read
Python | Pandas Index.intersection()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.intersection() function form the intersection of two Index objects. This returns a new Index with elements common to the in
2 min read
Python | Sympy Line.intersection() method
In Sympy, the function intersection() is used to find the intersection with another geometrical entity. Syntax: Line.intersection(o) Parameters: o: Point or LinearEntity Returns: intersection: list of geometrical entities Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) l1 =
1 min read
Python – Sympy Polygon.intersection() Method
In Sympy, the function Polygon.intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere. But can contain individual Points or c
2 min read
Most Efficient Way To Find The Intersection Of A Line And A Circle in Python
To make an efficient algorithm to find the intersection of a line and a circle, we need to understand what lines and circles are and how we can mathematically represent and calculate them in Python. Prerequisites LineCirclesQuadratics EquationsSolving a Quadratic EquationQuadratic Formula/Sridharacharya FormulaMathematical ApproachTo find the inter
8 min read
Find common elements in three sorted arrays by dictionary intersection
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, pri
4 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python string = "Geeksforgeeks" print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Find the longest common prefix between two strings after performing swaps on second string
Given two strings [Tex]a [/Tex]and [Tex]b [/Tex]. Find the longest common prefix between them after performing zero or more operations on string [Tex]b [/Tex]. In each operation, you can swap any two letters.Examples: Input : a = "here", b = "there" Output : 4 The 2nd string can be made "heret" by just swapping characters and thus the longest prefi
6 min read
Element-wise concatenation of two NumPy arrays of string
In this article, we will discuss how to concatenate element-wise two arrays of string Example : Input : A = ['Akash', 'Ayush', 'Diksha', 'Radhika'] B = ['Kumar', 'Sharma', 'Tewari', 'Pegowal'] Output : A + B = [AkashKumar, AyushSharma, 'DikshTewari', 'RadhikaPegowal'] We will be using the numpy.char.add() method. Syntax : numpy.char.add(x1, x2)Para
2 min read
Lexicographically smallest string which is not a subsequence of given string
Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a subsequence. Input: S = "aaaa"Output: aaabExplanat
5 min read
Sum of frequencies of characters of a string present in another string
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2. Examples: Input: S1 = "pPKf", S2 = "KKKttsdppfP"Output: 7Explanation:The character 'p' occurs twice in the string S2.The character 'P' occurs once in the string S2.The character 'K' occurs
5 min read
Python3 Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Python3 Program for Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
3 min read
Check if a string can be repeated to make another string
Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1. Examples: Input: a = "geeks", b = "geeksgeeks" Output: 2 "geeks" can be repeated twice to generate "geeksgeeks" Input: a = "df", b = "dfgrt" Output: -1 Recommended: Please try y
9 min read
Practice Tags :