VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-uncommon-characters-of-the-two-strings-set-2/

⇱ Find uncommon characters of the two strings using Bit Manipulation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find uncommon characters of the two strings using Bit Manipulation

Last Updated : 11 Jul, 2025

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.

Note: We have already discussed the naive approach using nested loops and an optimized approach using hash table to solve this problem in Find uncommon characters of the two strings.

Approach:

The idea is to use two variables that store the bitwiseOR 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 bitwise operations and bitwise XOR of these two integers will give the binary bit as 1 at only those positions that denote uncommon characters because bitwise XOR of oppositebit is 1. Print the character values for those positions.

Below is the implementation of the above approach:  


Output
bclpr

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.

Comment
Article Tags:
Article Tags: