#389
Find the Difference
EasyHash TableStringBit ManipulationSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a HashMap (or dictionary) to count the occurrences of each character in string s, then decrements the count for each character found in t. The character that remains with a count of 1 is the added character.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map for characters in string s.
- 2Step 2: Iterate through each character in string t, decrementing the count in the frequency map.
- 3Step 3: The character with a count of 1 in the frequency map is the added character.
solution.py9 lines
1from collections import Counter
2s_counter = Counter(s)
3for char in t:
4 if char in s_counter:
5 s_counter[char] -= 1
6 if s_counter[char] == 0:
7 del s_counter[char]
8 else:
9 print(char)ℹ
Complexity note: The time complexity is O(n) because we traverse both strings once. The space complexity is O(n) due to the storage of character counts in the HashMap.
- 1Using a frequency map can significantly reduce the time complexity.
- 2Understanding how to manipulate character counts is crucial for string problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.