25- Find the Difference
The problem can be found at the following link: Question Link
My Approach
Initialize an unordered_map called
mpto store character frequencies.Iterate through each character
cin strings:Increment the count of character
cin thempmap by 1.This loop populates the
mpmap with the frequency of each character in strings.
Iterate through each character
cin stringt:Decrement the count of character
cin thempmap by 1.Check if the count becomes less than 0. If it does, return the character
c. This character is the one that appears more times in stringtthan in strings, making it the "difference" character.
If no difference character is found during the loop in step 3, return the null character
'\0'. This indicates that all characters insandtare the same, and there is no additional character int.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(n)
Code (C++)
class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char,int> mp;
for(auto& c:s) mp[c]+=1;
for(auto& c:t) if(--mp[c]<0) return c;
return '\0';
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?