Solution: Find the Difference
Let's solve the Find the Difference problem using the Bitwise Manipulation pattern.
Statement
Given two strings, str1
and str2
, find the index of the extra character that is present in only one of the strings.
Note: If multiple instances of the extra character exist, return the index of the first occurrence of the character in the longer string.
Constraints:
-
str1.length
,str2.length
- Either
str2.length
str1.length + 1
, or,str1.length
str2.length + 1
- The strings consist of lowercase English letters.
Solution
So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.
Naive approach
The naive approach is to first sort both the strings. Then loop over the longer string and compare both strings, character by character. Finally, when one extra character is found in the longer string which does not match with the character at the corresponding index in the other string, we break out of the loop and return the index where the comparison failed.
The time complexity of this solution would be , that is . Here, is the cost of sorting one of the strings. The space complexity would be .
Optimized approach using bitwise manipulation
This solution utilizes the bitwise XOR manipulation to single out an extra character between two strings. It uses the property of the XOR operator of excluding matching pairs and leaves the unmatched (extra) character’s ASCII value. Initially, a variable is set to , and we iterate through each string, XOR the ASCII values of its characters with the variable, and store the result of each XOR operation in the same variable. Any character present in both strings cancels out because . The unmatched character, however, does not cancel out, and its ASCII value remains in the variable after all iterations. This value represents the extra character.
The algorithm proceeds through the following steps:
-
Initialize a variable,
result
, with to store the XOR result. -
Find the lengths of both strings.
-
Iterate over the characters of
str1
, and for each character, do the following operations:- Compute the ASCII value of the character.
- Perform a bitwise XOR operation between the current value of
result
and the ASCII value. - Store the result of the bitwise XOR operation back in
result
.
-
Now, iterate over the characters of
str2
and repeat the operations performed in step 3 for each character instr2
. -
After iterating over both strings, the
result
variable will correspond to the ASCII value of the extra character. -
Find and return the index of the extra character from the string with a greater length.
The slides below illustrate how we would like the algorithm to run:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.