Find the Difference

Easy Hash Maps

Problem

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

  • 0 ≤ s.length ≤ 10⁴
  • t.length == s.length + 1
  • s and t consist of lowercase English letters.

Example

Input: s = "abcd", t = "abcde"
Output: "e"

The brute-force approach would be to compare every character in s with every character in t, which is inefficient. Instead, the algorithm counts the frequency of each character in t, then subtracts the frequency of each character in s. The character with a frequency difference of 1 is the extra letter added. For example, counting characters in t yields {'a':1, 'b':1, 'c':1, 'd':1, 'e':1}. Subtracting counts from s removes the counts for 'a', 'b', 'c', and 'd', leaving 'e' with count 1, which is returned.

Approach

Straightforward Solution

A naive approach would compare each character in s against t, resulting in O(n^2) time complexity, which is inefficient for large strings.

Core Observation

The extra letter in t is the one whose frequency count exceeds that in s by exactly one. Counting characters and comparing frequencies reveals this difference directly.

Path to Optimal

Recognizing that frequency counts can be used to identify the extra character leads to a linear time solution. By counting characters in t and decrementing counts using s, the leftover character with count 1 is the added letter. This approach leverages a hash map for O(1) average lookup and update, reducing complexity to O(n).

Optimal Approach

Use a hash map to count the frequency of each character in t. Then iterate over s, decrementing the count for each character. Finally, iterate over the hash map to find the character with count 1, which is the extra letter added in t.

Time

O(n)

The solution iterates through both strings once each, performing O(1) average-time hash map operations per character, resulting in linear time complexity.

Space

O(1)

The hash map stores counts for lowercase English letters only, which is a fixed size of at most 26 entries, resulting in constant auxiliary space.

Pattern Spotlight

Hash Maps (Frequency Counting)

When comparing two collections where one has exactly one extra element, counting frequencies with a hash map and comparing counts efficiently reveals the difference in O(n) time.

Solution

1class Solution:
2 def findTheDifference(self, s: str, t: str) -> str:
3 counts = {}
4
5 for char in t:
6 counts[char] = counts.get(char, 0) + 1
7
8 for char in s:
9 counts[char] -= 1
10
11 for char, count in counts.items():
12 if count == 1:
13 return char
14
15 return ""

Step-by-Step Solution

1

Build Frequency Map for String t

3counts = {}
5for char in t:
6 counts[char] = counts.get(char, 0) + 1

Objective

To count the occurrences of each character in string t using a hash map.

Key Insight

Counting characters in t first captures the full frequency profile including the extra letter. Using a hash map allows O(1) average-time updates and lookups, enabling efficient frequency tracking.

Interview Quick-Check

Core Logic

The hash map stores character counts from t, which forms the baseline frequency profile including the extra letter.

Common Pitfalls & Bugs

Forgetting to initialize counts properly or using a data structure with slower lookups can degrade performance.

2

Subtract Frequency Counts Using String s

8for char in s:
9 counts[char] -= 1

Objective

To decrement the frequency counts for each character found in s, effectively removing characters that are common to both strings.

Key Insight

By subtracting counts for characters in s, the hash map reflects only the surplus counts from t. The character with a leftover count of 1 is the extra letter. This subtraction step is crucial to isolate the difference.

Interview Quick-Check

Core Logic

Decrementing counts for s's characters removes the shared characters, leaving the extra letter's count as 1.

Common Pitfalls & Bugs

Failing to decrement counts correctly or missing characters can lead to incorrect identification of the extra letter.

3

Identify and Return the Extra Letter

11for char, count in counts.items():
12 if count == 1:
13 return char

Objective

To find the character in the frequency map with a count of 1 and return it as the extra letter.

Key Insight

After adjusting counts, the extra letter is uniquely identified by having a count of exactly 1. Iterating over the hash map entries to find this character completes the solution efficiently.

Interview Quick-Check

Core Logic

The character with count 1 in the hash map is the extra letter added to t.

State & Boundaries

Return immediately upon finding the character with count 1 to avoid unnecessary iteration.

Common Pitfalls & Bugs

Not handling the case where no character has count 1 (though problem constraints guarantee one exists) could cause incorrect results.

4

Return Empty String if No Extra Letter Found (Fallback)

15return ""

Objective

To provide a fallback return value in case no extra letter is found, ensuring function completeness.

Key Insight

Though problem constraints guarantee an extra letter, returning an empty string handles unexpected inputs gracefully and satisfies function return requirements.

Interview Quick-Check

State & Boundaries

This return statement acts as a safety net, though it should never be reached under valid inputs.

Line Analysis

This solution has 2 Critical lines interviewers watch for.

Line 9 Critical
counts[char] -= 1

Decrement the count for the current character in the hash map.

This line is the core operation that isolates the extra letter by removing all characters present in s, ensuring only the added character remains with a positive count.

Line 12 Critical
if count == 1:

Check if the count for the character is exactly 1.

This conditional check is the decisive moment that confirms the identity of the extra letter, enabling immediate return.

Line 3 Core
counts = {}

Initialize an empty hash map to count character frequencies.

This data structure enables O(1) average-time insertion and lookup, which is essential for efficient frequency counting of characters.

Line 6 Core
counts[char] = counts.get(char, 0) + 1

Increment the count for the current character in the hash map.

Updating the count for each character builds the frequency profile needed to identify the extra letter after subtraction.

Line 13 Core
return char

Return the character identified as the extra letter.

Returning the extra letter completes the function, providing the required output as soon as it is found.

Line 11 Standard
for char, count in counts.items():

Iterate over each character and its count in the hash map.

Examining all entries allows detection of the character whose count indicates it is the extra letter.

Line 5 Standard
for char in t:

Iterate over each character in string t.

Processing every character in t ensures the frequency map captures the complete character distribution, including the extra letter.

Line 8 Standard
for char in s:

Iterate over each character in string s.

Processing s allows decrementing counts for characters common to both strings, isolating the extra letter in the frequency map.

Line 15 Basic
return ""

Return an empty string if no extra letter is found.

This fallback ensures the function returns a valid string in all cases, though problem constraints guarantee this line is never reached.

Test Your Understanding

Why does counting character frequencies and comparing them reveal the extra letter efficiently?

Because the extra letter in t increases its frequency count by exactly one compared to s, so by counting and subtracting frequencies, the letter with count one is uniquely identified as the added character.

Related Problems

Hash Maps pattern

Don't just read it. Drill it.

Reconstruct Find the Difference from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Find the Difference drill

or drill a free problem