Given two strings, where the second string is constructed using all characters of the first string except one, find the character that was skipped in the second string.

For example,

Input: first = ‘abc’, second = ‘ac’
Output: b
 
Input: first = ‘a’, second = ”
Output: a

You may assume valid input.

 
A simple solution is to store the count of each character of the second string in a map. Then, for each character in the first string, decrease its count. If the count of any character becomes negative at any point in time, we can say that the character is missing from the second string. However, this solution doesn’t take advantage of the fact that the second string is constructed from the first string, with only a single character skipped.

1. Using XOR of ASCII codes

The idea is to take the XOR of the ASCII codes of all characters in both strings. Since characters that occur twice cancel each other out, the result will be the ASCII code of the missing character. This will work on a valid input that satisfies the problem constraints.

C++


Download  Run Code

Output:

bb

Java


Download  Run Code

Output:

b

Python


Download  Run Code

Output:

b

 
The time complexity of the above solution is O(n), where n is the length of the first string. However, it uses two loops. The code can be optimized to run in a single loop, since the second string has just one character less than the first string. Here’s an optimized version of the above solution that processes both strings in a single iteration:

C++


Java


Python



2. Using Sum of ASCII codes

Another option is to keep track of the sum of the ASCII codes for each character in the second string. Then, deduct the ASCII code of each character of the first string from the total. At the end, all that is left is the ASCII code of the missing character from the second string.

C++


Download  Run Code

Output:

b

Java


Download  Run Code

Output:

b

Python


Download  Run Code

Output:

b

The time complexity of the above solution is O(n). As with the previous solution, the code can be further optimized to run in a single loop.