Given two strings, str1 and str2, the task is to find and print the uncommon characters of the two given strings in sorted order without using extra space. Here, an uncommon character means that either the character is present in one string or it is present in the other string but not in both. The strings contain only lowercase characters and can contain duplicates.
Input: str1 = “characters”, str2 = “alphabets” Output: b c l p r
Input: str1 = “geeksforgeeks”, str2 = “geeksquiz” Output: f i o q r u z
Approach: An approach that uses hashing has been discussed here. This problem can also be solved using bit operations. The approach uses 2 variables that store the bit-wise OR of the left shift of 1 with each character’s ASCII code – 97 i.e. 0 for ‘a’, 1 for ‘b’, and so on. 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.
Below is the implementation of the above approach:
Please Login to comment...