The Wayback Machine - https://web.archive.org/web/20241001044000/https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-python/
Open In App

Concatenated string with uncommon characters in Python

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

Two strings are given and you have to modify the 1st string such that all the common characters of the 2nd string have to be removed and the uncommon characters of the 2nd string have to be concatenated with the uncommon characters of the 1st string. 

Examples:

Input : S1 = “aacdb”, S2 = “gafd”
Output : “cbgf”
Input : S1 = “abcs”;, S2 = “cxzca”;
Output : “bsxz”

This problem has an existing solution please refer Concatenated string with uncommon characters of two strings link. We can solve this problem quickly in Python using Set and List Comprehension. The approach is simple,

  1. Convert both strings into a set so that they could have only unique characters. Now take the intersection of two sets to get the common character both strings have.
  2. Now separate out those characters in each string that are not common in both of them and concatenate the characters.

Implementation:

Python3




# Function to concatenated string with uncommon
# characters of two strings
 
def uncommonConcat(str1, str2):
 
    # convert both strings into set
    set1 = set(str1)
    set2 = set(str2)
 
    # take intersection of two sets to get list of
    # common characters
    common = list(set1 & set2)
 
    # separate out characters in each string
    # which are not common in both strings
    result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common]
 
    # join each character without space to get
    # final string
    print( ''.join(result) )
 
# Driver program
if __name__ == "__main__":
    str1 = 'aacdb'
    str2 = 'gafd'
    uncommonConcat(str1,str2)


Output

cbgf

Time Complexity: O(n+m), where n is length of str1 and m is length of str2
Auxiliary Space: O(m), where m is length of result list.

Approach#2: Using set symmetric difference 

We can use the symmetric difference operation of set to pull out all the uncommon character from both the string and make a string. 

Implementation:

Python3




# Function to concatenated string with uncommon
# characters of two strings
 
def uncommonConcat(str1, str2):
 
    # convert both strings into set
    set1 = set(str1)
    set2 = set(str2)
 
    # Performing symmetric difference operation of set
    # to pull out uncommon characters
    uncommon = list(set1 ^ set2)
 
    # join each character without space to get
    # final string
    print( ''.join(uncommon) )
 
# Driver program
if __name__ == "__main__":
    str1 = 'aacdb'
    str2 = 'gafd'
    uncommonConcat(str1,str2)


Output

fbgc

Approach #3: Using Counter() function

Python3




# Function to concatenated string with uncommon
# characters of two strings
from collections import Counter
 
 
def uncommonConcat(str1, str2):
 
    result = []
    frequency_str1 = Counter(str1)
    frequency_str2 = Counter(str2)
    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()
 
    print(''.join(set(result)))
 
 
# Driver program
if __name__ == "__main__":
    str1 = 'aacdb'
    str2 = 'gafd'
    uncommonConcat(str1, str2)


Output

cfbg

Approach #4 : Using two loops and no built-in module

In this approach we will use two loops and a variable to store the final result. We will iterate over the each string once and check that certain element is present in the other string or not, if not then we will just concatenate that character with our variable.

Python3




# Function to concatenate uncommon characters
# of two different strings
 
def concatenate_uncommon(str1,str2):
     
    # variable to store
    # the final string
     
    final_str = ''
     
    # iterating over first string
    # and checking each character is present
    # in the other string or not
    # if not then simply store that character
    # in the variable
     
    for i in str1:
        if i in str2:
            pass
        else:
            final_str+=i
             
    # iterating over second string
    # and checking each character is present
    # in the other string or not
    # if not then simply store that character
    # in the same variable as earlier
     
         
    for j in str2:
        if j in str1:
            pass
        else:
            final_str+=j
     
    # returning the final string as result
    return final_str
 
 
# Driver Code
 
# Example - 1
str1 = 'abcs'
str2 = 'cxzca'
print(concatenate_uncommon(str1,str2))
 
# Example - 2
str1 = 'aacdb'
str2 = 'gafd'
print(concatenate_uncommon(str1,str2))


Output

bsxz
cbgf
Time Complexity - O(n+m) # n = length of string 1 and m = length of string 2.
Auxiliary Space - O(1) # only one extra variable has been used


Similar Reads

Find resultant string after concatenating uncommon characters of given strings
Given two strings S1 and S2. The task is to concatenate uncommon characters of the S2 to S1 and return the resultant string S1 . Examples: Input: S1 = "aacdb", S2 = "gafd"Output: "cbgf" Input: S1 = "abcs", S2 = "cxzca";Output: "bsxz" Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Method 1: Using Hashmap Approac
13 min read
Find uncommon characters of the two strings
Find and print the uncommon characters of the two given strings in sorted order. Here uncommon character means that either the character is present in one string or it is present in another string but not in both. The strings contain only lowercase characters and can contain duplicates. Examples: Input: str1 = "characters", str2 = "alphabets" Outpu
10 min read
Reorder the given string to form a K-concatenated string
Given a string S and an integer K. The task is to form a string T such that the string T is a reordering of the string S in a way that it is a K-Concatenated-String. A string is said to be a K-Concatenated-String if it contains exactly K copies of some string.For example, the string "geekgeek" is a 2-Concatenated-String formed by concatenating 2 co
8 min read
Generate a string whose all K-size substrings can be concatenated to form the given string
Given a string str of size N and an integer K, the task is to generate a string whose substrings of size K can be concatenated to form the given string. Examples: Input: str = "abbaaa" K = 2 Output: abaa Explanation: All substring of size 2 of parent string "abaa" are "ab", "ba" and "aa". After concatenating all these substrings, the given string "
5 min read
Maximum number of times a given string needs to be concatenated to form a substring of another string
Given two strings S1 and S2 of length N and M respectively, the task is to find the maximum value of times the string S2 needs to be concatenated, such that it is a substring of the string S1. Examples: Input: S1 = "ababc", S2 = "ab"Output: 2Explanation: After concatenating S2 exactly twice, the string modifies to "abab". Therefore, string "abab" i
12 min read
Maximum Consecutive Zeroes in Concatenated Binary String
You are given a binary string str of length n. Suppose you create another string of size n * k by concatenating k copies of str together. What is the maximum size of a substring of the concatenated string consisting only of 0's? Given that k > 1. Examples: Input : str = "110010", k = 2 Output : 2 String becomes 110010110010 after two concatenati
8 min read
Print the final string when minimum value strings get concatenated in every operation
Given an array of strings and an array of integers where ith integer of the array corresponds to the value of the ith string present in the string array. Now pick two strings that have the smallest values in the integer array and sum up both the integers and concatenate the strings and add both the summed up integer to the integer array and the con
8 min read
Nth character in Concatenated Decimal String
If all decimal numbers are concatenated in a string then we will get a string that looks like string P as shown below. We need to tell the Nth character of this string. P = “12345678910111213141516171819202122232425262728293031….” Examples: N = 10 10th character is 1 N = 11 11th character is 0 N = 50 50th character is 3 N = 190 190th character is 1
9 min read
Print Kth character in sorted concatenated substrings of a string
Given a string of lower alphabetic characters, find K-th character in a string formed by substrings (of given string) when concatenated in sorted form. Examples: Input : str = “banana” K = 10Output : nAll substring in sorted form are,"a", "an", "ana", "anan", "anana", "b", "ba", "ban", "bana", "banan", "banana", "n", "na", "nan", "nana"Concatenated
15+ min read
Print uncommon elements from two sorted arrays
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements are present in both arrays. Input : arr1[] = {10, 20
6 min read
Longest Uncommon Subsequence
Given two strings, find the length of longest uncommon subsequence of the two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings which is not a subsequence of other strings. Examples: Input : "abcd", "abc"Output : 4The longest subsequence is 4 because "abcd"is a subsequence of first string, but n
12 min read
Shortest Uncommon Subsequence
Given two strings S and T, find the length of the shortest subsequence in S which is not a subsequence in T. If no such subsequence is possible, return -1. A subsequence is a sequence that appears in the same relative order, but is not necessarily contiguous. A string of length n has 2^n different possible subsequences. String S of length m (1 <
14 min read
Javascript Program to Print uncommon elements from two sorted arrays
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50}Output : 10 25 40 50We do not print 20 and 30 as theseelements are present in both arrays.Input : arr1[] = {10, 20, 30
2 min read
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated
Given two strings A and B of equal lengths, the task is to find an index i such that A[0...i] and B[i+1...n-1] give a palindrome when concatenated together. If it is not possible to find such an index then print -1. Examples: Input: S1 = "abcdf", S2 = "sfgba" Output: 1 S1[0..1] = "ab", S2[2..n-1] = "gba" S1 + S2 = "abgba" which is a palindrome. Inp
12 min read
Find the K-th minimum element from an array concatenated M times
Given an array arr[] and two integers K and M. The problem is to find the K-th Minimum element after concatenating the array to itself M times.Examples: Input : arr[] = {3, 1, 2}, K = 4, M = 3 Output : 4'th Minimum element is : 2 Explanation: Concatenate array 3 times (ie., M = 3) arr[] = [3, 1, 2, 3, 1, 2, 3, 1, 2] arr[] = [1, 1, 1, 2, 2, 2, 3, 3,
9 min read
Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string when concatenated with the strings of the sub-tree nodes becomes a pangram. Pangram: A pangram is a sentence containing every letter of the English Alphabet. Examples: Input: Output: 1 Only the weighted string of sub-tree of
7 min read
Count of pairs in a given range with sum of their product and sum equal to their concatenated number
Given two numbers A and B, the task is to find the count of pairs (X, Y) in range [A, B], such that (X * Y) + (X + Y) is equal to the number formed by concatenation of X and YExamples: Input: A = 1, B = 9 Output: 9 Explanation: The pairs (1, 9), (2, 9), (3, 9), (4, 9), (5, 9), (6, 9), (7, 9), (8, 9) and (9, 9) are the required pairs.Input: A = 4, B
5 min read
Count of pairs of Array elements which are divisible by K when concatenated
Given an array arr[] and an integer K, the task is to count the pair of indices (i, j) such that i !=j and concatenation of a[i] and a[j] is divisible by K. Example: Input: arr[] = [4, 5, 2], K = 2 Output: 4 Explanation: All possible concatenations are {45, 42, 54, 52, 24, 25}. Out of these, the numbers divisible by 2 are {42, 52, 24, 54}. Therefor
9 min read
Check if substrings from three given strings can be concatenated to form a palindrome
https://write.geeksforgeeks.org/internshipGiven three strings S1, S2, and S3 of lengths L, M, and N respectively, the task is to check if it is possible to choose some non-empty substrings from S1, S2, and S3 such that their concatenation is a palindrome. If found to be true, print "YES". Otherwise, print "NO". Examples: Input: S1 = "adcb", S2 = "b
5 min read
Maximum Pairs of Bracket Sequences which can be concatenated to form a Regular Bracket Sequence
Given an array arr[] of N strings such that each string consists of characters '(' and ')', the task is to find the maximum number of pairs of strings such that the concatenation of the two strings is a Regular Bracket Sequence. A Regular Bracket Sequence is a string consisting of brackets '(' and ')' such that every prefix from the beginning of th
9 min read
Count of strings to be concatenated with a character having frequency greater than sum of others
Given an array arr[] containing N strings, the task is to find the maximum number of strings that can be concatenated such that one character has a frequency greater than the sum of the frequencies of all others. Example: Input: arr[]: {"qpr, "pppsp, "t"}Output: 3Explanation: Concatenate all 3 strings to get: "aprpppspt". The frequency of character
9 min read
Removing Subsequence from concatenated Array
Given array A[] formed by the concatenation of string "ABC" one or multiple times. The task for this problem is to remove all occurrences of subsequence "ABC" by performing the following operation a minimum number of times. In one operation swap any two elements of array A[]. print the number of operations required and elements on which operations
7 min read
Check if Rotated Concatenated Strings are valid or not
Given a string s formed by concatenating another string s1 to itself, followed by a rotation to the left any number of times, the task is to determine whether a given string s is valid, indicating whether it can be formed from the original string s1. Examples: Input: s = "abcabc"Output: 1Explanation: s1 = "abcabc" can be generated by s = "abc". s+s
5 min read
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Check if a string can be made palindromic by swapping pairs of characters from indices having unequal characters in a Binary String
Given a string S and a binary string B, both of length N, the task is to check if the given string S can be made palindromic by repeatedly swapping characters at any pair of indices consisting of unequal characters in the string B. Examples: Input: S = "BAA", B = "100"Output: YesExplanation:Swapping S[0] and S[1] modifies S to "ABA" and B to "010".
15+ min read
Permutation of a string with maximum number of characters greater than its adjacent characters
Given a string str, the task is to print the maximum count of characters which are greater than both its left and right character in any permutation of the string. Examples: Input: str = "abc" Output: 1 Permutations of the string with the count of maximal character in each string are: abc - 0 acb - 1 Here a < c > b bac - 0 bca - 1 Here b <
11 min read
Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
Given string str of size N consists of lower-case English alphabets. The task is to find the arrangement of the characters of the string such that no two adjacent characters are neighbors in English alphabets. In case of multiple answers print any of them. If no such arrangement is possible then print -1.Examples: Input: str = "aabcd" Output: bdaac
6 min read
Count of ungrouped characters after dividing a string into K groups of distinct characters
Given a lower alphabetic string "S" of size N, and an integer K; the task is to find the count of characters that will remain ungrouped, after dividing the given string into K groups of distinct characters.Examples: Input: S = "stayinghomesaveslife", K = 1 Output: 6 Explanation: In the string S the elements whose occurrence is more than one time ar
6 min read
Make String repeating after every K characters by replacing characters at missing place
Given an string S and integer K and there are also some missing character i.e. ( _ ), the task is make the string S repeating after every K characters by replacing the appropriate character at missing place i.e. ( _ ). If it is not possible then print -1. Note: If there are multiple possible strings, then print the smallest lexicographically string
7 min read