GeeksforGeeks App
Open App
Browser
Continue

# 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 Sto S1  and return the resultant string S1 .

Examples:

Input: S1 = “aacdb”, S2 = “gafd”
Output: “cbgf”

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

Method 1:  Using Hashmap

Approach:

Below is the idea to solve the problem.

The idea is to use Hashmap where the key is a character and the value is an integer i.e. number of strings in which the character is present. If a character is present in one string, then the count is 1, else if the character is present in both strings, the count is 2.

Follow the steps below to implement the idea:

• Initialize the result as an empty string.
• Push all characters of S2 string in map with count as 1.
• Traverse first string and append all those characters to result that are not present in map then make their count 2.
• Traverse second string and append all those characters to result whose count is 1.

Below is the implementation of above approach:

## C++

 `// C++ program Find concatenated string with``// uncommon characters of given strings``#include ``using` `namespace` `std;` `string concatenatedString(string s1, string s2)``{``    ``string res = ``""``; ``// result` `    ``// store all characters of s2 in map``    ``unordered_map<``char``, ``int``> m;``    ``for` `(``int` `i = 0; i < s2.size(); i++)``        ``m[s2[i]] = 1;` `    ``// Find characters of s1 that are not``    ``// present in s2 and append to result``    ``for` `(``int` `i = 0; i < s1.size(); i++) {``        ``if` `(m.find(s1[i]) == m.end())``            ``res += s1[i];``        ``else``            ``m[s1[i]] = 2;``    ``}` `    ``// Find characters of s2 that are not``    ``// present in s1.``    ``for` `(``int` `i = 0; i < s2.size(); i++)``        ``if` `(m[s2[i]] == 1)``            ``res += s2[i];``    ``return` `res;``}` `/* Driver program to test above function */``int` `main()``{``    ``string s1 = ``"abcs"``;``    ``string s2 = ``"cxzca"``;``    ``cout << concatenatedString(s1, s2);``    ``return` `0;``}`

## Java

 `// Java program Find concatenated string with``// uncommon characters of given strings``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;` `class` `gfg {``    ``public` `static` `String concatenatedString(String s1,``                                            ``String s2)``    ``{``        ``// Result``        ``String res = ``""``;``        ``int` `i;` `        ``// creating a hashMap to add characters in string s2``        ``HashMap m``            ``= ``new` `HashMap();``        ``for` `(i = ``0``; i < s2.length(); i++)``            ``m.put(s2.charAt(i), ``1``);` `        ``// Find characters of s1 that are not``        ``// present in s2 and append to result``        ``for` `(i = ``0``; i < s1.length(); i++)``            ``if` `(!m.containsKey(s1.charAt(i)))``                ``res += s1.charAt(i);``            ``else``                ``m.put(s1.charAt(i), ``2``);` `        ``// Find characters of s2 that are not``        ``// present in s1.``        ``for` `(i = ``0``; i < s2.length(); i++)``            ``if` `(m.get(s2.charAt(i)) == ``1``)``                ``res += s2.charAt(i);` `        ``return` `res;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String s1 = ``"abcs"``;``        ``String s2 = ``"cxzca"``;``        ``System.out.println(concatenatedString(s1, s2));``    ``}``}` `/* This code is contributed by Devarshi_Singh*/`

## Python 3

 `# Python3 program Find concatenated string``# with uncommon characters of given strings`  `def` `concatenatedString(s1, s2):``    ``res ``=` `""  ``# result``    ``m ``=` `{}` `    ``# store all characters of s2 in map``    ``for` `i ``in` `range``(``0``, ``len``(s2)):``        ``m[s2[i]] ``=` `1` `    ``# Find characters of s1 that are not``    ``# present in s2 and append to result``    ``for` `i ``in` `range``(``0``, ``len``(s1)):``        ``if``(``not` `s1[i] ``in` `m):``            ``res ``=` `res ``+` `s1[i]``        ``else``:``            ``m[s1[i]] ``=` `2` `    ``# Find characters of s2 that are not``    ``# present in s1.``    ``for` `i ``in` `range``(``0``, ``len``(s2)):``        ``if``(m[s2[i]] ``=``=` `1``):``            ``res ``=` `res ``+` `s2[i]` `    ``return` `res`  `# Driver Code``if` `__name__ ``=``=` `"__main__"``:``    ``s1 ``=` `"abcs"``    ``s2 ``=` `"cxzca"``    ``print``(concatenatedString(s1, s2))` `# This code is contributed``# by Sairahul099`

## C#

 `// C# program Find concatenated string with``// uncommon characters of given strings``using` `System;``using` `System.Collections.Generic;` `class` `GFG {``    ``public` `static` `String concatenatedString(String s1,``                                            ``String s2)``    ``{``        ``// Result``        ``String res = ``""``;``        ``int` `i;` `        ``// creating a hashMap to add characters``        ``// in string s2``        ``Dictionary<``char``, ``int``> m``            ``= ``new` `Dictionary<``char``, ``int``>();``        ``for` `(i = 0; i < s2.Length; i++)``            ``if` `(!m.ContainsKey(s2[i]))``                ``m.Add(s2[i], 1);` `        ``// Find characters of s1 that are not``        ``// present in s2 and append to result``        ``for` `(i = 0; i < s1.Length; i++)``            ``if` `(!m.ContainsKey(s1[i]))``                ``res += s1[i];``            ``else``                ``m[s1[i]] = 2;` `        ``// Find characters of s2 that are not``        ``// present in s1.``        ``for` `(i = 0; i < s2.Length; i++)``            ``if` `(m[s2[i]] == 1)``                ``res += s2[i];` `        ``return` `res;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``String s1 = ``"abcs"``;``        ``String s2 = ``"cxzca"``;``        ``Console.WriteLine(concatenatedString(s1, s2));``    ``}``}` `// This code is contributed by PrinciRaj1992`

## Javascript

 ``

Output

`bsxz`

Time Complexity: O(M + N), where M and N represents the size of the given two strings.
Auxiliary Space: O(max(M, N)), where M and N represents the size of the given two strings.

Method 2: Using Set

Use a set instead of a hashmap to store the characters of the second string. This can simplify the code and reduce the space complexity.

Approach:

1. Initialize the result as an empty string.
2. Add all characters of S2 string in a set.
3. Traverse S1 string and append all those characters to result that are not present in the set.
4. Return the result.

Below is the implementation of the updated approach:

## C++

 `// C++ program Find concatenated string with``// uncommon characters of given strings``#include ``using` `namespace` `std;``string concatenatedString(string s1, string s2)``{``    ``string res = ``""``;``    ``unordered_set<``char``> s(s2.begin(), s2.end());` `    ``for` `(``int` `i = 0; i < s1.size(); i++) {``        ``if` `(s.find(s1[i]) == s.end())``            ``res += s1[i];``        ``else``            ``s.erase(s1[i]);``    ``}` `    ``for` `(``const` `char``& c : s)``        ``res += c;` `    ``return` `res;``}` `/* Driver program to test above function */``int` `main()``{``    ``string s1 = ``"abcs"``;``    ``string s2 = ``"cxzca"``;``    ``cout << concatenatedString(s1, s2);``    ``return` `0;``}`

## Java

 `import` `java.util.HashSet;` `public` `class` `ConcatenatedString {``    ``public` `static` `String concatenatedString(String s1, String s2) {``        ``String res = ``""``;``        ``HashSet s = ``new` `HashSet<>();``        ``for` `(``char` `c : s2.toCharArray()) {``            ``s.add(c);``        ``}` `        ``for` `(``char` `c : s1.toCharArray()) {``            ``if` `(!s.contains(c)) {``                ``res += c;``            ``} ``else` `{``                ``s.remove(c);``            ``}``        ``}` `        ``for` `(``char` `c : s) {``            ``res += c;``        ``}` `        ``return` `res;``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``String s1 = ``"abcs"``;``        ``String s2 = ``"cxzca"``;``        ``System.out.println(concatenatedString(s1, s2));``    ``}``}`

## C#

 `using` `System;``using` `System.Collections.Generic;` `public` `class` `Program``{``    ``public` `static` `string` `ConcatenatedString(``string` `s1, ``string` `s2)``    ``{``        ``string` `res = ``""``;``        ``HashSet<``char``> s = ``new` `HashSet<``char``>(s2);` `        ``for` `(``int` `i = 0; i < s1.Length; i++) {``            ``if` `(!s.Contains(s1[i]))``                ``res += s1[i];``            ``else``                ``s.Remove(s1[i]);``        ``}` `        ``foreach` `(``char` `c ``in` `s)``            ``res += c;` `        ``return` `res;``    ``}` `    ``public` `static` `void` `Main()``    ``{``        ``string` `s1 = ``"abcs"``;``        ``string` `s2 = ``"cxzca"``;``        ``Console.WriteLine(ConcatenatedString(s1, s2));``    ``}``}`

## Python3

 `def` `concatenatedString(s1: ``str``, s2: ``str``) ``-``> ``str``:``    ``res ``=` `""``    ``s ``=` `set``(s2)` `    ``for` `c ``in` `s1:``        ``if` `c ``not` `in` `s:``            ``res ``+``=` `c``        ``else``:``            ``s.remove(c)` `    ``res ``+``=` `"".join(s)` `    ``return` `res` `# Example usage``s1 ``=` `"abcs"``s2 ``=` `"cxzca"``print``(concatenatedString(s1, s2)) ``# Output: bsxz`

## Javascript

 `function` `concatenatedString(s1, s2) {``    ``let res = ``""``;``    ``let s = ``new` `Set(s2);` `    ``for` `(let i = 0; i < s1.length; i++) {``        ``if` `(!s.has(s1[i]))``            ``res += s1[i];``        ``else``            ``s.``delete``(s1[i]);``    ``}` `    ``for` `(let c of s)``        ``res += c;` `    ``return` `res;``}` `// Driver program to test above function``let s1 = ``"abcs"``;``let s2 = ``"cxzca"``;``console.log(concatenatedString(s1, s2));`

Output

`bszx`

Time Complaxity: O(M+N)
Auxiliary Space: O(N)

This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up