Leetcode 389. Find the Difference
LeetCode Problem 389: Find the Difference
You are given two strings s
and t
.
String t
is generated by randomly shuffling string s
and then adding one more letter at a random position.
Return the letter that was added to t
.
s = "abcd"
, t = "abcde"
e
0 <= s.length <= 1000
t.length == s.length + 1
s
and t
consist of lowercase English letters.s
be an empty string?
s
can be an empty string, and in that case, t
will have one letter.s
and t
consist of lowercase English letters only.s.length
is at most 1000. Performance should be considered within these constraints.We can solve this problem efficiently using the following methods:
s
and t
.t
will have a count difference due to being added.s
and t
), and only the extra character will remain.We’ll use the bit manipulation approach for its simplicity and efficiency.
#include <iostream>
#include <string>
char findTheDifference(std::string s, std::string t) {
char res = 0;
for(char c : s) {
res ^= c;
}
for(char c : t) {
res ^= c;
}
return res;
}
int main() {
std::string s = "abcd";
std::string t = "abcde";
std::cout << "The added letter is: " << findTheDifference(s, t) << std::endl; // Output: e
return 0;
}
The time complexity for this solution is O(n), where n
is the length of string s
(and by extension, t
is n+1
). This is because we are iterating through all characters in both strings exactly once.
The space complexity is O(1) since we are using a constant amount of extra space.
This approach ensures an efficient and clear solution to the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?