Skip to content

Commit 76c4790

Browse files
authored
Find-The-Difference Problem Pull Req (#129)
* added c++ solution for Find-The-Difference problem * Added Find The Difference problem to README Added Find The Difference problem to the Hashtable section
1 parent 8f375e4 commit 76c4790

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

C++/Find-The-Difference.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//time complexity O(n+m) where n and m are the number of input characters in each input string respectively
2+
//space compexity is O(1) since there is a limit on number of possible unique characters
3+
//loop through the first string and add a count of characters to hashmap
4+
//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
5+
//else if the letter cannot be found in our hashmap, then this must be the extra character
6+
//Otherwise if no differences can be found between the two input strings we just return null character
7+
8+
9+
10+
class Solution {
11+
public:
12+
char findTheDifference(string s, string t) {
13+
14+
char returnChar= '\0';
15+
std::unordered_map <char,int>ourMap;
16+
17+
//count the letters in the input string and add it to map
18+
for (const char& letter:s) {
19+
20+
if(ourMap.find(letter)==ourMap.end()){ ourMap[letter]=1;}
21+
else{ourMap[letter]++;}
22+
}
23+
24+
25+
//compare with letters in other string
26+
for (const char& letter:t){
27+
28+
//if you can find the letter then decrement it
29+
if(ourMap.find(letter)!=ourMap.end()) {
30+
31+
ourMap[letter]--;
32+
if(ourMap[letter]<0) { return letter; }
33+
34+
}
35+
36+
else{return letter;}
37+
}
38+
39+
return returnChar;
40+
41+
}
42+
};

README.md

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

244245
<br/>
245246
<div align="right">

0 commit comments

Comments
 (0)