Python - String uncommon characters
Last Updated :
28 Apr, 2025
One of the string operation can be computing the uncommon characters of two strings i.e, output the uncommon values that appear in both strings. This article deals with computing the same in different ways.
Method 1: Using set() + symmetric_difference() Set in python usually can perform the task of performing set operations such as set symmetric difference. 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 the symmetric difference is performed using symmetric_difference(). Returns the sorted set.
Python3
# Python 3 code to demonstrate
# String uncommon characters
# using set() + symmetric_difference()
# 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)
# String uncommon characters
# using set() + symmetric_difference()
res = set(test_str1).symmetric_difference(test_str2)
# printing symmetric_difference
print("The string uncommon elements are : " + str(res))
OutputThe original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string uncommon elements are : {'a', 'C', 'G', 'd'}
Method 2 : Using join() join() performs the task similar to list comprehension in case of lists. This encapsulates whole symmetric_difference logic and joins together each element filtered through the symmetric_difference logic into one string, hence computing the symmetric_difference. It converts the strings into set and then computed ^ operation on them.
Python3
# Python 3 code to demonstrate
# String uncommon characters
# using join()
# 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 join() to
# String uncommon characters
res = ''.join(sorted(set(test_str1) ^ set(test_str2)))
# printing symmetric_difference
print("The string uncommon elements are : " + str(res))
OutputThe original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string uncommon elements are : CGad
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #3: Using Counter() function
Python3
# Python 3 code to demonstrate
# String uncommon characters
from collections import Counter
# 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)
frequency_str1 = Counter(test_str1)
frequency_str2 = Counter(test_str2)
result = []
for key in frequency_str1:
if key not in frequency_str2:
result.append(key)
for key in frequency_str2:
if key not in frequency_str1:
result.append(key)
# Sorting the result
result.sort()
# printing symmetric_difference
print("The string uncommon elements are : " + str(result))
OutputThe original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string uncommon elements are : ['C', 'G', 'a', 'd']
Time Complexity: O(n*m), where n is length of frequency_str1 and m is length of frequency_str2.
Auxiliary Space: O(n), where n is length of result list.
Method #4: Using numpy:
Algorithm:
- Import the numpy module.
- Initialize two strings test_str1 and test_str2.
- Print the original strings.
- Convert the strings to lists using list() method.
- Using numpy setdiff1d() function, compute the difference between the two lists, i.e., uncommon characters in the first list.
- Similarly, compute the difference for the second list.
- Concatenate the two results using numpy concatenate() method to get the final uncommon characters
- Print the uncommon characters.
Python3
import numpy as np
# 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)
# String uncommon characters using numpy
res = np.setdiff1d(list(test_str1), list(test_str2))
res = np.concatenate((res, np.setdiff1d(list(test_str2), list(test_str1))))
# printing uncommon characters
print("The string uncommon elements are : " + str(res))
# This code is contributed by Rayudu.
Output:
The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string uncommon elements are : ['G' 'C' 'a' 'd']
Time Complexity: O(m + n log n), where m and n are the lengths of the input strings. Converting the strings to lists takes O(m+n) time. The setdiff1d() function takes O(n log n) time for sorting and O(n) time for finding the unique elements. Therefore, the overall time complexity of this method is O(m + n log n).
Auxiliary Space: O(m + n), where m and n are the lengths of the input strings. Converting the strings to lists takes O(m+n) space. The setdiff1d() function takes O(n) space for creating the output array. Therefore, the overall space complexity of this method is O(m + n).
Method #5: Using heapq:
Algorithm:
- Initialize two strings "test_str1" and "test_str2".
- Print the initial strings.
- Find the symmetric difference between two sets of the characters of the given strings using the set difference operator.
- Merge the resultant sets obtained in step 3 using the heapq.merge() method.
- Store the merged set in a list.
- Print the list obtained in step 5 as the output.
Python3
import heapq
# 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 heapq to find symmetric difference
res = list(heapq.merge(set(test_str1) - set(test_str2),
set(test_str2) - set(test_str1)))
# printing symmetric_difference
print("The string uncommon elements are : " + str(res))
# This code is contributed by Jyothi pinjala.
OutputThe original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string uncommon elements are : ['G', 'a', 'C', 'd']
Time Complexity:
The time complexity for the set difference operation is O(n), where n is the length of the string. The time complexity of the heapq.merge() method is O(n log n) for n elements. Therefore, the overall time complexity of the algorithm is O(n log n).
Auxiliary Space:
The space complexity of the algorithm is O(n), as we are using sets to store the characters of the given strings and a list to store the merged set.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read