15% off all plans & roadmaps Use code
See plansFind the Difference
Updated
TL;DR: Find the one letter that t has and s lacks, even though t is a shuffle of s. XOR every character of both strings, and each letter that appears in both cancels out, leaving only the added letter in O(n) time and O(1) space.
Problem
You are given two strings, s and t. String t is made by shuffling the letters of s and then inserting one extra letter at a random position. Return the letter that was added to t.
Example 1
Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added.
Example 2
Input: s = "", t = "y" Output: "y"
Constraints
0 <= s.length <= 1000t.length == s.length + 1sandtconsist of lowercase English letters.
Constraints that matter
- n up to 1000 is small enough that even the O(n^2) count scan passes, so the constraint does not force the optimal answer. You choose XOR for its O(n) time and O(1) space.
- t.length == s.length + 1 guarantees exactly one extra letter. Every other letter comes in a matching pair, which is the property XOR and counting depend on.
- Only lowercase letters appear, so every code point is between 97 and 122. A 26-slot count array is enough, and XOR results stay below 128 with no overflow risk.
- s can be empty. The solution must handle zero iterations over s and still return the single letter in t.
Hints
Hint 1
The order of letters in t is noise.
Hint 2
Take each letter of t in turn and count how often it appears in t and in s.
Solution
Intuition
The order of letters in t is noise. Shuffling changes positions and nothing else, so only the letter counts matter. Once you see that the question is about counts, you can look for a shortcut that cancels matching pairs.
Picture a row of light switches, one per letter. Each letter from s flips its switch, and each letter from t flips it again, so only the extra letter's switch stays on.
Bitwise XOR cancels pairs. Any value XORed with itself gives 0, and XOR with 0 leaves a value unchanged. Every letter of s has a twin in t, so XORing all letters from both strings removes every pair and keeps only the extra letter.
Name the pattern: bitwise XOR for finding a single or missing value. Look for a list where every value appears twice except one, or where a full set has one value removed. The answer is the XOR of everything you read.
XOR does not care about order. The shuffle and the random insert position are harmless, so you never need to know where the extra letter sits.
Worked example
Input: s = "zzxyyx", t = "xzyzyxq" Output: "q" Explanation: String s holds z, z, x, y, y, x. String t holds x, z, y, z, y, x, q. Every letter count matches except q, which appears once in t and never in s. The letters that appear in both strings cancel, so q is the answer.
Approach 1: Brute force: count each letter
Take each letter of t in turn and count how often it appears in t and in s. The added letter is the first one whose counts differ, because it appears one more time in t. Every other letter has the same count in both strings, so it cannot be the answer. This is the naive scan most people write first.
Steps
- Loop over each character
choft, in order. - Count how many times
chappears int. - Count how many times
chappears ins. - If the two counts differ, return
ch. - Return an empty string if nothing differs. The constraints rule this out.
Dry run
Trace on s = zzxyyx and t = xzyzyxq. Letters x, z and y each appear 2 times in t and 2 times in s, so they match. Letter q appears 1 time in t and 0 times in s, so the counts differ and the function returns q. The loop never reaches a mismatch before q.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the length of s, so t has n + 1 letters. The outer loop runs up to n + 1 times. Each run scans t and s, about 2n + 1 characters, so the total work is about (n + 1)(2n + 1), which is O(n^2). The only extra memory is two counters, so the space is O(1).
Approach 2: Sort, then compare
What is slow in the brute force is the repeated counting. It rebuilds the same counts again and again. The insight that fixes it: sorting puts equal letters next to each other, so one left-to-right comparison finds the extra letter.
Both sorted strings agree until the extra letter's place. From there t runs one step ahead, so the first mismatch holds the extra letter. If nothing mismatches, the extra letter is the last one in sorted t.
Steps
- Make a sorted copy of
s. - Make a sorted copy of
t. - Loop index i from 0 to len(s) - 1.
- If the sorted copies differ at index i, return the character of sorted
tat index i. - If the loop finishes, return the last character of sorted
t.
Dry run
Sorted s is xxyyzz. Sorted t is qxxyyzz. At index 0, x and q differ, so the function returns q. The loop stops there, and index 1 is never read.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the length of s. Sorting each string with a comparison sort costs O(n log n), and t has n + 1 letters, so the two sorts together stay O(n log n). The comparison loop does at most n steps, which is less than the sort cost. The sorted copies hold about 2n characters, so the space is O(n).
The Bitwise XOR - Finding Single/Missing Number infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Bitwise XOR - Finding Single/Missing Number
Part of Bit Manipulation Patterns
Approach 3: One-pass XOROptimalBitwise XOR - Finding Single/Missing Number
What is slow in the sort is the work spent putting letters in order. You never need an order. You need only the letter that has no partner. The insight that fixes it: XOR of a value with itself is 0, so pairs cancel as you read them, and no counts or order are needed.
Start with an accumulator at 0. XOR every letter of both strings into it. Each letter from s meets its matching letter from t and cancels to 0. The accumulator ends as the code of the extra letter.
The accumulator holds one code, not a count. That is why one integer is enough.
Why it is correct. The invariant is that acc always equals the XOR of every character read so far. Each letter of s has a matching copy in t, and XOR of a pair is 0, so those pairs vanish. Since the extra letter has no partner, it is the only value left, and no step discards a character.
Steps
- Set
accto 0. - XOR the code of each character of
sintoacc. - XOR the code of each character of
tintoacc. - Convert
accback to a character and return it.
Dry run
Trace on s = zzxyyx and t = xzyzyxq. The codes are z = 122, x = 120, y = 121, q = 113. Each row shows the accumulator after one XOR.
| Step | Read | Code | acc after |
|---|---|---|---|
| 1 | s[0] z | 122 | 122 |
| 2 | s[1] z | 122 | 0 |
| 3 | s[2] x | 120 | 120 |
| 4 | s[3] y | 121 | 1 |
| 5 | s[4] y | 121 | 120 |
| 6 | s[5] x | 120 | 0 |
| 7 | t[0] x | 120 | 120 |
| 8 | t[1] z | 122 | 2 |
| 9 | t[2] y | 121 | 123 |
| 10 | t[3] z | 122 | 1 |
| 11 | t[4] y | 121 | 120 |
| 12 | t[5] x | 120 | 0 |
| 13 | t[6] q | 113 | 113 |
The accumulator ends at 113, which is q.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of s, so t has n + 1 characters. The loops XOR each character exactly once, which is 2n + 1 operations, so the time is O(n). Each XOR works on one integer, and the only other state is the loop index, so the space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
result = 0
# Python strings cannot be XORed directly, so convert with ord
for ch in s:
result ^= ord(ch)
for ch in t:
result ^= ord(ch)
return chr(result)Common mistakes
if counts[idx] == 0in the counting loop fires on a matched letter. With s = ab and t = abb, the first a drops to 0 and the code returns a. Checkcounts[idx] < 0so only the extra letter triggers the return.return acc;in Java or C#, orreturn accin JavaScript, returns a number instead of a character. Cast with(char) accin Java and C#, or callString.fromCharCode(acc)in JavaScript.acc = s[0]followed by a loop from index 1 breaks when s is empty, because s[0] does not exist. Startaccat 0 and XOR every character of s.for ch in sused as the only pass in the count method misses the extra letter when it is new. With s = a and t = ab, b never appears in s, so the count must come from t as well.for i in range(len(t))readinga[i]in the sort comparison runs past the end of the sorted s. Loop only up to len(s) - 1, then return the last character of sorted t.
Edge cases
- s is empty and t is one letter, such as s = `` and t = y. The answer is y. The XOR loop over s does nothing, and the accumulator holds the code of y.
- The added letter equals a letter already in s, such as s = ab and t = abb. The answer is b. This input catches the
== 0counting bug. - The added letter sorts first, such as s = bc and t = abc. The answer is a. The sorted comparison returns at index 0.
- Repeated letters in both strings, such as s = zzz and t = zzzz. The answer is z. Counts reach 3 and 4, and XOR still cancels three pairs and keeps one z.
- Maximum size, with s of length 1000. Lowercase codes are 97 to 122, so the XOR accumulator stays below 128 and cannot overflow a 32-bit int.
- Position of the extra letter, such as s = cab and t = bcda. The answer is d. Where the letter sits in t does not change any approach.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Find the Difference, with how to answer them.
Unlock the follow-upsFind the Difference FAQ
What is the time complexity of Find the Difference?
The XOR solution runs in O(n) time, where n is the length of s, because it reads each character of s and t once. The sort solution costs O(n log n), and the count-each-letter brute force costs O(n^2).
Why use bitwise XOR for Find the Difference?
XOR cancels equal values, because x XOR x is 0 and x XOR 0 is x. Every letter of s has a matching copy in t, so those pairs vanish and the extra letter remains. No counts or sorting are needed.
Can Find the Difference be solved in O(1) extra space?
Yes. The XOR accumulator is one integer, and a 26-slot count array also has constant size. The sort approach needs O(n) for its sorted copies, so it does not meet this bound.
Why can't I XOR the strings directly in Python?
The caret operator works on integers, not on str. Convert each character with ord, XOR the integers, and turn the result back with chr. Java and C# need a cast from int to char before building the string.
Is XOR better than a hash map for this problem?
Both run in O(n) time with constant extra space here, because the alphabet has 26 letters. XOR needs no array and no index arithmetic, so it is shorter. A hash map works for any alphabet, so it is the safer choice if the input can contain other characters.
Asked at
See which companies ask this — Pro
Related problems
- Single Number · same technique: Bitwise XOR - Finding Single/Missing Number
- Missing Number · same technique: Bitwise XOR - Finding Single/Missing Number
- Sum of Two Integers · same technique: Bitwise XOR - Finding Single/Missing Number
- Single Number II · same technique: Bitwise XOR - Finding Single/Missing Number
- Counting Bits · same pattern: Bit Manipulation Patterns
- Reverse Bits · same pattern: Bit Manipulation Patterns
- Number of 1 Bits · same pattern: Bit Manipulation Patterns
- Power of Two · same pattern: Bit Manipulation Patterns
- Power of Four · same pattern: Bit Manipulation Patterns
- Pow(x, n) · same pattern: Bit Manipulation Patterns