Skip to content

Find-The-Difference Problem Pull Req #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions C++/Find-The-Difference.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//time complexity O(n+m) where n and m are the number of input characters in each input string respectively
//space compexity is O(1) since there is a limit on number of possible unique characters
//loop through the first string and add a count of characters to hashmap
//loop through second string and for each letter lookup in hashmap. If found, decrement the count in the hasmap. If the count <0 for any letter then we have found our extra character
//else if the letter cannot be found in our hashmap, then this must be the extra character
//Otherwise if no differences can be found between the two input strings we just return null character



class Solution {
public:
char findTheDifference(string s, string t) {

char returnChar= '\0';
std::unordered_map <char,int>ourMap;

//count the letters in the input string and add it to map
for (const char& letter:s) {

if(ourMap.find(letter)==ourMap.end()){ ourMap[letter]=1;}
else{ourMap[letter]++;}
}


//compare with letters in other string
for (const char& letter:t){

//if you can find the letter then decrement it
if(ourMap.find(letter)!=ourMap.end()) {

ourMap[letter]--;
if(ourMap[letter]<0) { return letter; }

}

else{return letter;}
}

return returnChar;

}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
| 049 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [Python](./Python/group_anagram.py) | _O(nlogn)_ | _O(1)_ | Easy | |
| 554 | [Brick Wall](https://leetcode.com/problems/brick-wall/) | [C++](./C++/brick-walls.cpp) | _O(n)_ | _O(n)_ | Medium | |
| 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Javascript](../JavaScript/146.LRU-Cache.js) | _O(log(n))_ | _O(n)_ | Medium | |
| 389 | [Find The Difference](https://leetcode.com/problems/find-the-difference/) | [C++](../C++/Find-The-Difference.cpp) | _O(n)_ | _O(1)_ | Easy | |

<br/>
<div align="right">
Expand Down