Find the Difference — LeetCode 389 Python Solution

EasyBit ManipulationHash TableStringSorting
Problem
#389
Reading time
2 min

The problem

You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position.

Example

Input
s = "abcd", t = "abcde"
Output
"e"
Explanation
'e' is the letter that was added.

Python solution

Python
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        cnt = Counter(s)
        for c in t:
            cnt[c] -= 1
            if cnt[c] < 0:
                return c

Complexity

MeasureComplexity
TimeO(n)
SpaceO(|\Sigma|), where n is the length of the string, and \Sigma represents the character set auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 389. Find the Difference is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 389. Find the Difference?
LeetCode 389. Find the Difference is rated Easy on LeetCode.
What is the time complexity of LeetCode 389. Find the Difference?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 389. Find the Difference?
The Python solution on this page uses O(|\Sigma|), where n is the length of the string, and \Sigma represents the character set auxiliary space.
What topics does LeetCode 389. Find the Difference cover?
LeetCode 389. Find the Difference is tagged Bit Manipulation, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview