Magicsheet logo

Find the Difference

Easy
50%
Updated 8/1/2025

Find the Difference

What is this problem about?

The Find the Difference interview question is a character-tracking task. You are given two strings, ss and tt. String tt is generated by shuffling string ss and then adding one additional character at a random position. Your goal is to identify and return that single added character.

Why is this asked in interviews?

Companies like Microsoft and Amazon ask the Find the Difference coding problem to assess a candidate's basic data structure knowledge. While a hash map is a valid solution, interviewers often look for the O(1)O(1) space Bit Manipulation approach. It’s a great introductory problem to test optimization awareness within a String interview pattern.

Algorithmic pattern used

This problem can be solved with three different patterns:

  1. Hash Table: Count character frequencies in ss and compare with frequencies in tt.
  2. ASCII Sum: Calculate the sum of ASCII values of all characters in tt and subtract the sum of ASCII values in ss. The remainder is the character code of the extra letter.
  3. XOR (Optimized): XOR all characters in both ss and tt. Since XORing a character with itself results in 0, all paired characters cancel out, leaving only the added character.

Example explanation

s="abcd"s = "abcd", t="abcde"t = "abcde"

  • ASCII Sum:
  • Sum(s) = 'a' + 'b' + 'c' + 'd'
  • Sum(t) = 'a' + 'b' + 'c' + 'd' + 'e'
  • Result = Sum(t) - Sum(s) = 'e'.
  • XOR:
  • ('a'^'b'^'c'^'d') ^ ('a'^'b'^'c'^'d'^'e')
  • Paired chars become 0: 0 ^ 0 ^ 0 ^ 0 ^ 'e' = 'e'.

Common mistakes candidates make

  • Sorting: Using sorting (O(NlogN)O(N \log N)) instead of linear search (O(N)O(N)).
  • String Concatenation: Trying to remove characters one-by-one from tt, which can be O(N2)O(N^2) depending on the language.
  • Ignoring Case: Not confirming if the strings are case-sensitive.

Interview preparation tip

Whenever you have a problem involving finding a "unique" or "odd-one-out" element in a set of pairs, think XOR. It is the most efficient Bit Manipulation interview pattern for these scenarios.

Similar Questions