Skip to content
Problem 389 · LeetCode 389(opens in a new tab)

Find the Difference

EasyBit manipulation

You get two strings of lower-case letters, s and t. To make t, someone took the letters of s, shuffled them, and slipped in one more letter somewhere.

Return that extra letter. It may be a letter that already appears in s.

Example 1

Input:  s = "lid", t = "dial"
Output: "a"
Why:    d, i and l come from s; a is new
2 more examples and the constraints

Example 2

Input:  s = "", t = "q"
Output: "q"
Why:    t has a single letter, and it is the extra one

Example 3

Input:  s = "aa", t = "aaa"
Output: "a"
Why:    t has one more a than s

Constraints

  • 0 ≤ length of s ≤ 1,000
  • Length of t = length of s + 1
  • Both strings hold only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort both stringsO(n log n)
  2. Count lettersO(n)
  3. XOR every letterO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for strings of 1,000 lettersVerdict
Sort both stringsO(n log n)
Passes; sorts for no reason
Count lettersO(n)
Passes; easy to explain
XOR every letterO(n)
Best; no extra memory

n = length of t.

Edge cases to test

  • s is empty. t has one letter, and that letter is the answer.
  • The extra letter is already in s. "aa" and "aaa": a set of letters sees no difference, but counts or XOR do.
  • Added at the end. Sorted strings never mismatch, so the answer is the last letter of sorted t.
  • All letters the same. "zzzz" and "zzzzz": the answer is "z".

Common mistakes

  • Using a set of letters, which misses an extra copy of a letter that s already has.
  • Comparing s and t position by position without sorting; t is shuffled.
  • Forgetting to turn the XOR result back into a character.

How to talk through it

  1. 1Clarify. Only lower-case letters? Can the extra letter repeat one from s? Can s be empty?
  2. 2Start simple. Sorting both strings shows the extra letter at the first mismatch.
  3. 3Count instead. A 26-slot count drops the sort: the letter whose count is already 0 is extra.
  4. 4Cancel with XOR. Pairs cancel, so XOR of all codes is the extra letter. O(n) time, O(1) space.
  5. 5Test out loud. Run an empty s, a repeated letter, and a letter added at the end.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?