![]() |
VOOZH | about |
Given two strings s1 and s2, the task is to find the uncommoncharacters in both strings. An uncommon character means that the character is present in only one string or in another string but not in both. The strings contain only lowercase characters and can have duplicates.
Note: Output the uncommon characters in sorted order.
Examples:
Input: s1 = "geeksforgeeks", s2 = "geeksquiz"
Output: "fioqruz"
Explanation: The characters 'f', 'i', 'o', 'q', 'r', 'u', and 'z' are present in either s1 or s2, but not in both.Input: s1 = "characters", s2 = "alphabets"
Output: "bclpr"
Explanation: The characters 'b', 'c', 'l', 'p', and 'r' are present in either s1 or s2, but not in both.Input: s1 = "rome", s2 = "more"
Output: ""
Explanation: Both strings contain the same characters, so there are no unique characters. The output is an empty string.
Table of Content
The idea is to use nested loops: for each character in string s1,check whether it is present in string s2 or not. Likewise, for each character in string s2, check whether it is present in string s1 or not. Create an array check[] of size MAX_CHAR (where MAX_CHAR is set to 26 for lowercase English letters) to flag the already used characters. Store the uncommon characters in a character array or string. Finally, sort the characters in ascending order and print the result.
bclpr
The idea is to use a hash table , present[], of size MAX_CHAR (set to 26 for the lowercase English alphabet), to store the characters of each string. First, iterate through the string s1 and mark each character in the present[] array with the value 1. Then, iterate through the string s2, and update the present[] array: mark characters already seen in s1 with the value -1 and mark new characters in s2 with the value 2. Finally, collect all characters marked as unique (i.e., those with value 1 or 2), and return them in sorted order.
Note the MAX_CHAR is alphabet size of input characters which is typically a constant. If we have only lower case characters, then MAX_CHAR is 26 only. If we consider all ASCII characters, then MAX_CHAR is 256.
bclpr
The approach uses 2 variables that store the bit-wise OR of the left shift of 1 with each character’s ASCII code. For both the strings, we get an integer after performing these bit-wise operations. Now the XOR of these two integers will give the binary bit as 1 at only those positions that denote uncommon characters. Print the character values for those positions. Please refer to Find uncommon characters of the two strings using Bit Manipulation for implementation.