Start learning free

LESSON 300 OF 671 · BRUTE FORCE

Find the Difference

Practice O(n2)

You get two strings, s and t. To make t, someone shuffled s and added one extra letter.

Return the extra letter as a character.

 

Example 1:

Input: s = "plan", t = "nlapk"
Output: k
Explanation: t is "plan" shuffled, plus a 'k'.

Example 2:

Input: s = "moon", t = "noomo"
Output: o
Explanation: s has two o's.
t has three o's.
The extra letter is an 'o'.

Example 3:

Input: s = "", t = "w"
Output: w

 

Constraints:

  • s has 0 to 1,000 letters.
  • t has exactly one more letter than s.
  • Both strings use only lowercase English letters.

The extra letter has to be a letter that appears in t. So we can iterate through every character of t and ask: "is this the extra one?"

A character i is the extra one if and only if it appears more times in t than in s. We can compare the count of i in both strings.

JavaScript doesn't have a built-in count method, so we'll write a small helper countChar(str, ch) that loops through str and tallies matches. Then we can use it like:
for (const i of t) {
    if (this.countChar(s, i) !== this.countChar(t, i)) {
        return i;
    }
}


This brute-force approach is O(n2) because each countChar call walks the whole string, and we do it for every character. It's the simplest place to start; later solutions improve to O(n).
STEP 1 OF 9
    Ctrl + Enter to check