Skip to content
Related Articles

Related Articles

Find uncommon characters of the two strings

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 10 Nov, 2022
Improve Article
Save Article

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. 
Source: Amazon Interview Experience | Set 355 (For 1 Year Experienced)

Examples: 

Input: str1 = “characters”, str2 = “alphabets” 
Output: b c l p r

Input: str1 = “geeksforgeeks”, str2 = “geeksquiz” 
Output: f i o q r u z

Recommended Practice

Naive Approach: Using two loops, for each character of 1st string check whether it is present in the 2nd string or not. Likewise, for each character of 2nd string check whether it is present in the 1st string or not.

Note: In the practice area of gfg the string has to be sorted in order to match with the output. 

Below is the implementation of the above approach:

C++




// C++ implementation to find the uncommon
// characters of the two strings
#include <bits/stdc++.h>
using namespace std;
 
// function to find the uncommon characters
// of the two strings
void findAndPrintUncommonChars(string str1, string str2)
{
    // to store the answer
    string ans = "";
     
      // to handle the case of duplicates
    vector<int> used(26, false);
 
    // check first for str1
    for (int i = 0; i < str1.size(); i++) {
        // keeping a flag variable
        bool found = false;
 
        for (int j = 0; j < str2.size(); j++) {
            // if found change the flag
            // and break from loop
            if (str1[i] == str2[j]) {
                found = true;
                break;
            }
        }
 
        // if duplicate character not found
        // then add it to ans
        if (!found and !used[str1[i] - 'a']) {
            used[str1[i] - 'a'] = true;
            ans += str1[i];
        }
    }
 
    // now check for str2
    for (int i = 0; i < str2.size(); i++) {
        // keeping a flag variable
        bool found = false;
 
        for (int j = 0; j < str1.size(); j++) {
            // if found change the flag
            // and break from loop
            if (str2[i] == str1[j]) {
                found = true;
                break;
            }
        }
 
        // if duplicate character not found
        // then add it to ans
        if (!found and !used[str2[i] - 'a']) {
            used[str2[i] - 'a'] = true;
            ans += str2[i];
        }
    }
 
    // to match with output
    sort(ans.begin(), ans.end());
 
      // if not found any character
    if (ans.size() == 0)
        cout << "-1";
     
      // else print the answer
      else
        cout << ans << " ";
}
 
// Driver program to test above
int main()
{
    string str1 = "characters";
    string str2 = "alphabets";
    findAndPrintUncommonChars(str1, str2);
    return 0;
}

Java




// Java implementation to find the uncommon
// characters of the two strings
import java.util.*;
 
public class Solution
{
 
  // function to find the uncommon characters
  // of the two strings
  static void findAndPrintUncommonChars(String str1,
                                        String str2)
  {
    // to store the answer
    String ans = "";
 
    // to handle the case of duplicates
    boolean[] used = new boolean[26];
 
    // check first for str1
    for (int i = 0; i < str1.length(); i++)
    {
 
      // keeping a flag variable
      boolean found = false;
 
      for (int j = 0; j < str2.length(); j++)
      {
 
        // if found change the flag
        // and break from loop
        if (str1.charAt(i) == str2.charAt(j)) {
          found = true;
          break;
        }
      }
 
      // if duplicate character not found
      // then add it to ans
      if (!found && !used[str1.charAt(i) - 'a']) {
        used[str1.charAt(i) - 'a'] = true;
        ans += str1.charAt(i);
      }
    }
 
    // now check for str2
    for (int i = 0; i < str2.length(); i++)
    {
 
      // keeping a flag variable
      boolean found = false;
 
      for (int j = 0; j < str1.length(); j++)
      {
 
        // if found change the flag
        // and break from loop
        if (str2.charAt(i) == str1.charAt(j)) {
          found = true;
          break;
        }
      }
 
      // if duplicate character not found
      // then add it to ans
      if (!found && !used[str2.charAt(i) - 'a']) {
        used[str2.charAt(i) - 'a'] = true;
        ans += str2.charAt(i);
      }
    }
 
    // to match with output
    char tempArray[] = ans.toCharArray();
 
    // Sorting temp array using
    Arrays.sort(tempArray);
    ans = new String(tempArray);
 
    // if not found any character
    if (ans.length() == 0)
      System.out.println("-1");
 
    // else print the answer
    else
      System.out.println(ans + " ");
  }
 
  // Driver program to test above
  public static void main(String[] args)
  {
    String str1 = "characters";
    String str2 = "alphabets";
    findAndPrintUncommonChars(str1, str2);
  }
}
 
// This code is contributed by karandeep1234

C#




// C# implementation to find the uncommon
// characters of the two strings
using System;
 
public class GFG {
 
    // function to find the uncommon characters
    // of the two strings
    static void findAndPrintUncommonChars(string str1,
                                          string str2)
    {
        // to store the answer
        string ans = "";
 
        // to handle the case of duplicates
        bool[] used = new bool[26];
 
        // check first for str1
        for (int i = 0; i < str1.Length; i++) {
 
            // keeping a flag variable
            bool found = false;
 
            for (int j = 0; j < str2.Length; j++) {
 
                // if found change the flag
                // and break from loop
                if (str1[i] == str2[j]) {
                    found = true;
                    break;
                }
            }
 
            // if duplicate character not found
            // then add it to ans
            if (!found && !used[str1[i] - 'a']) {
                used[str1[i] - 'a'] = true;
                ans += str1[i];
            }
        }
 
        // now check for str2
        for (int i = 0; i < str2.Length; i++) {
 
            // keeping a flag variable
            bool found = false;
 
            for (int j = 0; j < str1.Length; j++) {
 
                // if found change the flag
                // and break from loop
                if (str2[i] == str1[j]) {
                    found = true;
                    break;
                }
            }
 
            // if duplicate character not found
            // then add it to ans
            if (!found && !used[str2[i] - 'a']) {
                used[str2[i] - 'a'] = true;
                ans += str2[i];
            }
        }
 
        // to match with output
        char[] tempArray = ans.ToCharArray();
 
        // Sorting temp array using
        Array.Sort(tempArray);
        ans = new String(tempArray);
 
        // if not found any character
        if (ans.Length == 0)
            Console.WriteLine("-1");
 
        // else print the answer
        else
            Console.WriteLine(ans + " ");
    }
 
    // Driver program to test above
    public static void Main(string[] args)
    {
        string str1 = "characters";
        string str2 = "alphabets";
        findAndPrintUncommonChars(str1, str2);
    }
}
 
// This code is contributed by karandeep1234

Output

bclpr 

Time Complexity: O(n1*n2)
Auxiliary Space:  O(1), as a constant-size array is used to handle duplicates.

Efficient Approach: An efficient approach is to use hashing

  • Use a hash table of size 26 for all the lowercase characters.
  • Initially, mark the presence of each character as ‘0’ (denoting that the character is not present in both strings).
  • Traverse the 1st string and mark the presence of each character of 1st string as ‘1’ (denoting 1st string) in the hash table.
  • Now, traverse the 2nd string. For each character of the 2nd string, check whether its presence in the hash table is ‘1’ or not. If it is ‘1’, then mark its presence as ‘-1’ (denoting that the character is common to both the strings), else mark its presence as ‘2’ (denoting 2nd string).

Below image is a dry run of the above approach:

Below is the implementation of the above approach:

C++




// C++ implementation to find the uncommon
// characters of the two strings
#include <bits/stdc++.h>
using namespace std;
 
// size of the hash table
const int MAX_CHAR = 26;
 
// function to find the uncommon characters
// of the two strings
void findAndPrintUncommonChars(string str1, string str2)
{
    // mark presence of each character as 0
    // in the hash table 'present[]'
    int present[MAX_CHAR];
    for (int i=0; i<MAX_CHAR; i++)
        present[i] = 0;
 
    int l1 = str1.size();
    int l2 = str2.size();
 
    // for each character of str1, mark its
    // presence as 1 in 'present[]'
    for (int i=0; i<l1; i++)
        present[str1[i] - 'a'] = 1;
 
    // for each character of str2
    for (int i=0; i<l2; i++)
    {
        // if a character of str2 is also present
        // in str1, then mark its presence as -1
        if (present[str2[i] - 'a'] == 1
            || present[str2[i] - 'a'] == -1)
            present[str2[i] - 'a'] = -1;
 
        // else mark its presence as 2
        else
            present[str2[i] - 'a'] = 2;
    }
 
    // print all the uncommon characters
    for (int i=0; i<MAX_CHAR; i++)
        if (present[i] == 1 || present[i] == 2 )
            cout << (char(i + 'a')) << " ";
}
 
// Driver program to test above
int main()
{
    string str1 = "characters";
    string str2 = "alphabets";
    findAndPrintUncommonChars(str1, str2);
    return 0;
}

Java




// Java implementation to find the uncommon
// characters of the two strings
class GFG
{
 
    // size of the hash table
    static int MAX_CHAR = 26;
 
    // function to find the uncommon
    // characters of the two strings
    static void findAndPrintUncommonChars(String str1,
                                       String str2)
    {
        // mark presence of each character as 0
        // in the hash table 'present[]'
        int present[] = new int[MAX_CHAR];
        for (int i = 0; i < MAX_CHAR; i++)
        {
            present[i] = 0;
        }
 
        int l1 = str1.length();
        int l2 = str2.length();
 
        // for each character of str1, mark its
        // presence as 1 in 'present[]'
        for (int i = 0; i < l1; i++)
        {
            present[str1.charAt(i) - 'a'] = 1;
        }
 
        // for each character of str2
        for (int i = 0; i < l2; i++)
        {
             
            // if a character of str2 is also present
            // in str1, then mark its presence as -1
            if (present[str2.charAt(i) - 'a'] == 1
                || present[str2.charAt(i) - 'a'] == -1)
            {
                present[str2.charAt(i) - 'a'] = -1;
            }
             
            // else mark its presence as 2
            else
            {
                present[str2.charAt(i) - 'a'] = 2;
            }
        }
 
        // print all the uncommon characters
        for (int i = 0; i < MAX_CHAR; i++)
        {
            if (present[i] == 1 || present[i] == 2)
            {
                System.out.print((char) (i + 'a') + " ");
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "characters";
        String str2 = "alphabets";
        findAndPrintUncommonChars(str1, str2);
    }
}
 
// This code is contributed by Rajput-JI

Python 3




# Python 3 implementation to find the
# uncommon characters of the two strings
 
# size of the hash table
MAX_CHAR = 26
 
# function to find the uncommon characters
# of the two strings
def findAndPrintUncommonChars(str1, str2):
     
    # mark presence of each character as 0
    # in the hash table 'present[]'
    present = [0] * MAX_CHAR
    for i in range(0, MAX_CHAR):
        present[i] = 0
 
    l1 = len(str1)
    l2 = len(str2)
     
    # for each character of str1, mark its
    # presence as 1 in 'present[]'
    for i in range(0, l1):
        present[ord(str1[i]) - ord('a')] = 1
         
    # for each character of str2
    for i in range(0, l2):
         
        # if a character of str2 is also present
        # in str1, then mark its presence as -1
        if(present[ord(str2[i]) - ord('a')] == 1 or
           present[ord(str2[i]) - ord('a')] == -1):
            present[ord(str2[i]) - ord('a')] = -1
 
        # else mark its presence as 2
        else:
            present[ord(str2[i]) - ord('a')] = 2
 
    # print all the uncommon characters
    for i in range(0, MAX_CHAR):
        if(present[i] == 1 or present[i] == 2):
            print(chr(i + ord('a')), end = " ")
 
# Driver Code
if __name__ == "__main__":
    str1 = "characters"
    str2 = "alphabets"
    findAndPrintUncommonChars(str1, str2)
 
# This code is contributed
# by Sairahul099

C#




// C# implementation to find the uncommon
// characters of the two strings
using System;
 
class GFG
{
 
    // size of the hash table
    static int MAX_CHAR = 26;
 
    // function to find the uncommon
    // characters of the two strings
    static void findAndPrintUncommonChars(String str1,
                                    String str2)
    {
        // mark presence of each character as 0
        // in the hash table 'present[]'
        int []present = new int[MAX_CHAR];
        for (int i = 0; i < MAX_CHAR; i++)
        {
            present[i] = 0;
        }
 
        int l1 = str1.Length;
        int l2 = str2.Length;
 
        // for each character of str1, mark its
        // presence as 1 in 'present[]'
        for (int i = 0; i < l1; i++)
        {
            present[str1[i] - 'a'] = 1;
        }
 
        // for each character of str2
        for (int i = 0; i < l2; i++)
        {
             
            // if a character of str2 is also present
            // in str1, then mark its presence as -1
            if (present[str2[i] - 'a'] == 1
                || present[str2[i] - 'a'] == -1)
            {
                present[str2[i] - 'a'] = -1;
            }
             
            // else mark its presence as 2
            else
            {
                present[str2[i] - 'a'] = 2;
            }
        }
 
        // print all the uncommon characters
        for (int i = 0; i < MAX_CHAR; i++)
        {
            if (present[i] == 1 || present[i] == 2)
            {
                Console.Write((char) (i + 'a') + " ");
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String str1 = "characters";
        String str2 = "alphabets";
        findAndPrintUncommonChars(str1, str2);
    }
}
 
// This code is contributed by PrinciRaj1992

Javascript




<script>
// Javascript implementation to find the uncommon
// characters of the two strings
 
// size of the hash table
var MAX_CHAR = 26;
 
// function to find the uncommon characters
// of the two strings
function findAndPrintUncommonChars(str1, str2)
{
    // mark presence of each character as 0
    // in the hash table 'present[]'
    var present = Array(MAX_CHAR);
    for (var i = 0; i < MAX_CHAR; i++)
        present[i] = 0;
 
    var l1 = str1.length;
    var l2 = str2.length;
 
    // for each character of str1, mark its
    // presence as 1 in 'present[]'
    for (var i = 0; i < l1; i++)
        present[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 1;
 
    // for each character of str2
    for (var i = 0; i < l2; i++)
    {
        // if a character of str2 is also present
        // in str1, then mark its presence as -1
        if (present[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] == 1
            || present[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] == -1)
            present[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] = -1;
 
        // else mark its presence as 2
        else
            present[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 2;
    }
 
    // print all the uncommon characters
    for (var i=0; i<MAX_CHAR; i++)
        if (present[i] == 1 || present[i] == 2 )
            document.write( (String.fromCharCode(i + 'a'.charCodeAt(0))) + " ");
}
 
// Driver program to test above
var str1 = "characters";
var str2 = "alphabets";
findAndPrintUncommonChars(str1, str2);
 
// This code is contributed by importantly.
</script>

Output

b c l p r 

Time Complexity: O(m + n), where m and n are the sizes of the two strings respectively.
Auxiliary Space: O(1), no any other extra space is required, so it is a constant.

Another map based approach:

  • Take two maps and initialize their value as 0. 
  • traverse the first string, for each character present in first string, set 1 in the 1st map.
  • Do the same for second string also.
  • Iterate through all 26 characters, if the xor of map 1 and map 2 is 1 then it is present in one of the string only. i.e those characters are uncommon characters. Add them in the result string.
  • return the result string, if the string is empty, return -1.

This approach is contributed by  Bibhash Ghosh.

Below is the implementation of the above approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
string UncommonChars(string a, string b)
{
    int mp1[26] = {0}, mp2[26] = {0};
    int n = a.size(), m = b.size();
 
    for(auto &x: a){
      mp1[x-'a'] = 1;
    }
 
    for(auto &x: b){
      mp2[x-'a'] = 1;
    }
 
    string chars = "";
 
    for(int i = 0; i < 26; ++i){
      if(mp1[i]^mp2[i])
        chars+=char(i+'a');
    }
    if(chars == "")
      return "-1";
    else
      return chars;
}
 
int main(){
    string a = "geeksforgeeks";
    string b = "geeksquiz";
    string result = UncommonChars(a,b);
    cout << result << endl;
    return 0;
}

Java




// Java implementation to find the uncommon
// characters of the two strings
class GFG {
 
    // size of the hash table
    static int MAX_CHAR = 26;
 
    // function to find the uncommon
    // characters of the two strings
    static String UncommonChars(String a, String b)
    {
        int mp1[] = new int[MAX_CHAR];
        int mp2[] = new int[MAX_CHAR];
        int n = a.length();
        int m = b.length();
        for (int i = 0; i < n; i++) {
            mp1[a.charAt(i) - 'a'] = 1;
        }
        for (int i = 0; i < m; i++) {
            mp2[b.charAt(i) - 'a'] = 1;
        }
 
        String chars = "";
        for (int i = 0; i < 26; i++) {
            if ((mp1[i] ^ mp2[i]) != 0) {
                chars += (char)(i + 'a');
            }
        }
        if (chars == "")
            return "-1";
        else
            return chars;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String a = "geeksforgeeks";
        String b = "geeksquiz";
        String result = UncommonChars(a, b);
        System.out.print(result);
    }
}
 
// This code is contributed by Aarti_Rathi

C#




using System;
 
public static class GFG {
  public static string UncommonChars(string a, string b)
  {
    int[] mp1 = new int[26];
    int[] mp2 = new int[26];
    int n = a.Length;
    int m = b.Length;
 
    foreach(var x in a) { mp1[x - 'a'] = 1; }
 
    foreach(var x in b) { mp2[x - 'a'] = 1; }
 
    string chars = "";
 
    for (int i = 0; i < 26; ++i) {
      if ((mp1[i] ^ mp2[i]) != 0) {
        chars += (char)(i + 'a');
      }
    }
    if (chars == "") {
      return "-1";
    }
    else {
      return chars;
    }
  }
 
  public static void Main()
  {
    string a = "geeksforgeeks";
    string b = "geeksquiz";
    string result = UncommonChars(a, b);
    Console.Write(result);
    Console.Write("\n");
  }
}
 
// This code is contributed by Aarti_Rathi

Javascript




function UncommonChars(a, b)
{
     
    let mp1 = [], mp2 = [];
    for(let i = 0; i < 26; i++)
    {
        mp1.push(0);
        mp2.push(0);
    }
    let n = a.length, m = b.length;
 
    for(let i = 0; i < n; i++) {
        let index = a.charCodeAt(i) - 97;
      mp1[index] = 1;
    }
 
    for(let i = 0; i < m; i++)
    {
        let index = b.charCodeAt(i) - 97;
      mp2[index] = 1;
    }
 
    let chars = "";
     for(let i = 0; i < 26; ++i){
      if(mp1[i]^mp2[i])
          {
              let char = String.fromCharCode(97+i);
              chars += char;
          }
    }
    if(chars == "")
      return "-1";
    else
      return chars;
}
 
    let a = "geeksforgeeks";
    let b = "geeksquiz";
    let result = UncommonChars(a,b);
    console.log(result);
     
    // This code is contributed by garg28harsh.

Output

fioqruz

Time Complexity: O(m+n), Where m is the length of the first string and n is the length of second string.
Auxiliary Space: O(1), no any other extra space is required, so it is a constant.

This article is contributed by Ayush Jauhari. 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
Related Articles

Start Your Coding Journey Now!