EasyNo. 0389
Find the Difference — LeetCode 389 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Hash Table, String, Sorting
- Reading time
- 2 min
- Source
- leetcode.com
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
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 cComplexity
- Time
- O(n)
- Space · auxiliary
- O(|Σ|), where n is the length of the string, and Σ represents the character set
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
| No. | Problem | Difficulty |
|---|---|---|
| 2215 | Find the Difference of Two Arrays | Easy |
| 2135 | Count Words Obtained After Adding a Letter | Medium |
| 0049 | Group Anagrams | Medium |
| 0187 | Repeated DNA Sequences | Medium |
| 0242 | Valid Anagram | Easy |
| 0268 | Missing Number | Easy |
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(|Σ|), 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.