Find the Difference — LeetCode 389 Python Solution
EasyBit ManipulationHash TableStringSorting
- Problem
- #389
- Pattern
- Bit Manipulation
- 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
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 cComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(|\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.