Given two strings. write a Python program to find which letters are in the two strings but not in both.
Example:
Input: india australia Output: s t r n d u l
Steps to be performed:
- Take two string inputs and store them in different variables.
- Convert them into a set and look for letters inside in two strings but not in both.
- Store those letters in a different list.
- Print that list.
Below is the implementation of the above approach:
Python3
# taking string inputs string_1 = "hi" string_2 = "virat" # letters which are present in the two strings # but not in both are found using the ‘^’ operator e = list ( set (string_1) ^ set (string_2)) # printing finale list print ( "The letters are:" ) for i in e: print (i) |
The letters are: r v t h a
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using Counter() function
Python3
from collections import Counter # taking string inputs string_1 = "hi" string_2 = "virat" res = [] freq1 = Counter(string_1) freq2 = Counter(string_2) for i in freq1: if i not in freq2.keys(): res.append(i) for i in freq2: if i not in freq1.keys(): res.append(i) # printing finale list print ( "The letters are:" ) for i in res: print (i) |
The letters are: h v r a t
Time Complexity: O(N)
Auxiliary Space : O(N)
Method 4: Using Filter and Lambda
Step-by-step algorithm for implementing the Python Program that Displays Letters that are not common in two strings Using Filter and Lambda approach:
Input:
Two strings, string_1 and string_2
Output:
List of letters that are not common in both strings
Steps:
Convert string_1 and string_2 into sets to get unique characters
Find the letters that are present in both string_1 and string_2, but not in both, using filter and lambda functions
Concatenate the two filtered lists
Print the list of letters that are not common in both strings
Python3
string_1 = "hi" string_2 = "virat" #letters which are present in the two strings #but not in both are found using filter and lambda result = list ( filter ( lambda x: x not in set (string_2), set (string_1))) + list ( filter ( lambda x: x not in set (string_1), set (string_2))) #printing finale list print ( "The letters are:" ) for i in result: print (i) |
The letters are: h a t v r
Time complexity:
Converting a string into a set takes O(n) time, where n is the length of the string
Lambda function is executed for each character in the two strings, so it takes O(n) time where n is the total length of both strings
Concatenating two lists takes O(m) time where m is the length of the combined list
Printing the final list takes O(k) time, where k is the length of the list
Therefore, the total time complexity is O(n )
Auxiliary space complexity:
Creating two sets requires O(n + m) space where n and m are the lengths of the two strings
The filter function returns a list, so it requires O(n) space
The final result list requires O(k) space
Therefore, the total auxiliary space complexity is O(n )