Find the Difference

Find the one letter added to a shuffled copy of a string, by letting matching letters cancel out with XOR.

Given two strings s and t, where t was made by shuffling the letters of s and adding one more letter at a random position, return the letter that was added.

Example 1
Input: s = "abcd", t = "abcde"
Output: 'e'
Example 2
Input: s = "", t = "y"
Output: 'y'
Example 3
Input: s = "ab", t = "bab"
Output: 'b'
Solution

The Idea

Picture four letter tiles in a bag: a, b, c and d. A friend copies them, slips in one more tile, shakes the bag and hands it back. In Example 1 the new bag holds a, b, c, d and e, and with so few tiles you see at once that e is the newcomer.

Example 3 is trickier. The string s is "ab" and t is "bab". Every letter of t also appears in s, so asking "which letter of t is missing from s?" finds nothing. The added tile is a second 'b'. What gives it away is a count: 'b' appears once in s and twice in t.

Now put the letters of both strings in one row: a, b, then b, a, b. Each letter of s has a twin somewhere in t, so cross out the twins in pairs. The two a's go, then two of the three b's, and one 'b' is left: the added letter. Can a program cross out pairs like that without tracking which letter is which?

It can, because a Java char is a number, its character code. The letter 'a' has the code 97 and 'b' has 98. In binary, 97 is 1100001 and 98 is 1100010, with the bit positions numbered from 0 on the right. The operation XOR, written ^ in Java, compares two numbers bit by bit. Each result bit is 1 where the two bits differ and 0 where they match.

So 97 ^ 98 is 0000011: the two codes differ at positions 0 and 1 and match everywhere else. Two facts follow from the bit-by-bit rule. A code XORed with itself gives 0, since every bit matches, and XOR with 0 leaves a code unchanged. Order does not matter either, because a position ends up 1 exactly when an odd number of the codes have a 1 there.

Look at the picture below. Each row takes one letter, shown in the column labelled "the letter in binary", and XORs it into the column labelled "running XOR".

XOR of every letter of s = ab and t = bab, written as 7 bits with position 0 on the right. The running XOR goes 1100001, 0000011, 1100001, 0000000 and ends at 1100010, which is 98, the letter b.

The row labelled 'a' from s starts the running XOR at 'a' itself. After 'b' from s it reads 0000011, which is no letter at all, and that is fine. In the row labelled 'b' from t, the two b's cancel and 1100001, the code of 'a', comes back. The next row cancels the two a's and leaves all zeros.

The last row XORs the final 'b' into those zeros, and the running XOR ends at 1100010, which is 98, the letter 'b'. Each matching pair cancels wherever its two letters sit, so the shuffle makes no difference, and the one letter without a twin is what remains.

Solution Approach

Turning that idea into code means weighing it against the simpler ways of sorting or counting, then settling how to keep the running XOR and how to turn it back into a letter. Adding up the codes is a close alternative to XOR.

Sorting or counting the letters

What would a first attempt look like? One way is to sort both strings and walk along them side by side until they differ. For "ab" and "bab" the sorted strings are "ab" and "abb", and they part at the third place, where t has 'b'. Sorting a string of n letters takes O(n log n) time, more than one pass over the letters.

Another way is to count each letter of t, subtract one for each letter of s, and return the letter whose count stays at 1. That takes a single pass, but it needs a table of counts. A set of the letters of s is not enough, because in Example 3 both letters of t are in the set {a, b}. XOR keeps the counting idea, odd or even, in a single number.

Keeping the running XOR

Where does the running XOR live? In one int named x that starts at 0, since XOR with 0 changes nothing. A Java int has 32 bits, and its top bit marks negative numbers in the form called two's complement. A char code has 16 bits and is never negative, so the upper 16 bits of x stay 0 throughout.

Since order does not matter, the program can XOR all of s first and then all of t. The picture follows that same order.

Turning the result back into a letter

After both loops, what is in x? The code of the added letter, 98 for Example 3. Writing (char) x turns that number back into the letter 'b' for printing.

Adding the codes instead

Is XOR the one trick that works? Adding the codes of t and subtracting the codes of s also leaves the added letter: 98 + 97 + 98 - 97 - 98 is 98 for Example 3. The difference is in the size of the numbers along the way. The sum grows with the strings, while the running XOR never needs more than the 16 bits of a char code.

Java Solution

The method findTheDifference works in these steps:

  1. First, set an int named x to 0. It holds the running XOR.
  2. Loop over s with an index i, and XOR each character s.charAt(i) into x.
  3. A second loop does the same for every character of t. Each letter of t with a twin in s cancels that twin out of x.
  4. After the second loop, x holds the code of the added letter, so return (char) x.

The main method uses a small helper, run, that prints both strings and the letter found. It runs the three examples, then "aab" with a third 'a' added, and "hello" shuffled with a 'z' at the end.

Java
public class FindTheDifference {

    public static char findTheDifference(String s, String t) {
        int x = 0;
        for (int i = 0; i < s.length(); i++) {
            x ^= s.charAt(i);
        }
        for (int i = 0; i < t.length(); i++) {
            x ^= t.charAt(i);     // a letter that appears in both strings cancels out
        }
        return (char) x;          // only the added letter is left
    }

    static void run(String s, String t) {
        System.out.println("s = \"" + s + "\", t = \"" + t + "\" -> '"
                + findTheDifference(s, t) + "'");
    }

    public static void main(String[] args) {
        run("abcd", "abcde");
        run("", "y");
        run("ab", "bab");
        run("aab", "abaa");
        run("hello", "ohlelz");
    }
}

Running it prints:

Output
s = "abcd", t = "abcde" -> 'e'
s = "", t = "y" -> 'y'
s = "ab", t = "bab" -> 'b'
s = "aab", t = "abaa" -> 'a'
s = "hello", t = "ohlelz" -> 'z'

Look at the line for "ab" and "bab": it prints 'b', the letter in the last row of the picture. In the line for an empty s, the first loop never runs, so x is simply the code of 'y'.

The line for "aab" and "abaa" prints 'a'. The two strings hold five a's together, an odd number, so four cancel in pairs and one is left, while the two b's cancel completely. In the last line, the two l's of "hello" sit in other places in "ohlelz", yet they still cancel, and 'z' remains.

Complexity

The method reads each character of both strings once and keeps a single number.

  • Time: O(n), with n the length of t, because each of its n letters and each of the n - 1 letters of s is XORed into x once.
  • Space: O(1), because x is one int however long the strings are, and charAt reads the strings without copying them.

The same cancelling idea solves Single Number and Missing Number.