Solutions to Leetcode 389. Find the Difference

Solutions to Leetcode 389. Find the Difference

Problem statement

You are given two strings s and t.

String t is generated by random shuffling string s and then adding one more letter at a random position.

Return the letter that was added to t.

Example 1

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

Example 2

Input: s = "", t = "y"
Output: "y"

Constraints

  • 0 <= s.length <= 1000.
  • t.length == s.length + 1.
  • s and t consist of lowercase English letters.

Solution 1: Check the appearance of each character

For each character in t, check if it appears in s. If so mark that character in s as visited.

Example 3

Let s = "ababadbcb" and t = "abadbbcbda". When reaching character 'd' in t you cannot find it in s.

#include <iostream>
#include <vector>
using namespace std;
char findTheDifference(string s, string t) {
    char a;
    vector<bool> visited(s.size());
    for (const char& c : t) {
        int i = 0;
        while (i < s.size()) {
            if (!visited[i] && s[i] == c) {
                visited[i] = true;
                break;
            }
            i++;
        }
        if (i == s.size()) { // not found in s
            a = c;
            break;
        }
    }
    return a;
}
int main() {
    cout << findTheDifference("abcd", "bdcea") << endl;
    cout << findTheDifference("", "y") << endl;
}
Output:
e
y

Complexity

  • Runtime: O(N*N), where N = s.length.
  • Extra space: O(N).

Solution 2: Rearranging the strings

Sort the strings and you can easily identify which character in t was added.

Example 3

Sorting s = "ababadbcb" and t = "abadbbcbda" you get s = aaabbbbc and t = aaabbbbcd. Every position of t has the same character as in s except the last one.

#include <iostream>
#include <algorithm>
using namespace std;
char findTheDifference(string s, string t) {
    sort(s.begin(), s.end());
    sort(t.begin(), t.end());
    for (int i=0; i < s.size(); i++) {
        if (s[i] != t[i]) {
            return t[i];
        }
    }
    return t.back();
}
int main() {
    cout << findTheDifference("abcd", "abdce") << endl;
    cout << findTheDifference("", "y") << endl;
}
Output:
e
y

Complexity

  • Runtime: O(NlogN), where N = s.length.
  • Extra space: O(1).

Solution 3: Counting the appearances

Count the appearance of each character of the string s then check which character of string t was not counted.

Example 3

Counting the appearances of the characters in s = "ababadbcb", you get:

count['a'] = 3;
count['b'] = 4;
count['c'] = 1;

Then with t = "abadbbcbda" you can identify the character 'd' was not counted.

#include <iostream>
#include <unordered_map>
using namespace std;
char findTheDifference(string s, string t) {
    unordered_map<char, int> m;
    char a;
    for (const char& c : s) {
        m[c]++;
    }
    for (const char& c : t) {
        m[c]--;
        if (m[c] < 0) {
            a = c;
            break;
        }
    }
    return a;
}
int main() {
    cout << findTheDifference("abcd", "abdce") << endl;
    cout << findTheDifference("", "y") << endl;
}
Output:
e
y

Complexity

  • Runtime: O(N), where N = s.length.
  • Extra space: O(N).

Solution 4: Set Subtraction

Consider s, t are multisets of characters. Then the result of the subtraction t-s is what you want for this problem.

Example 1

s = {'a', 'b', 'c', 'd'};
t = {'a', 'b', 'c', 'd', 'e'};
t - s = 'e'.
#include <iostream>
using namespace std;
char findTheDifference(string s, string t) {
    int a = 0;
    for (const char& c : t) {
        a += c;
    }
    int b = 0;
    for (const char& c : s) {
        b += c;        
    }
    return a - b;
}
int main() {
    cout << findTheDifference("abcd", "abdce") << endl;
    cout << findTheDifference("", "y") << endl;
}
Output:
e
y

Note that in this solution, you have applied the fact the value of a char is an int.

Complexity

  • Runtime: O(N), where N = s.length.
  • Extra space: O(1).

Solution 5: Modern C++ with std::accumulate

You can also use the function std::accumulate from the Standard Library to compute the sums in the Solution 4.

#include <numeric>
#include <iostream>
using namespace std;
char findTheDifference(string s, string t) {
    return accumulate(t.begin(), t.end(), 0) - accumulate(s.begin(), s.end(), 0);
}
int main() {
    cout << findTheDifference("abcd", "abdce") << endl;
    cout << findTheDifference("", "y") << endl;
}
Output:
e
y

Complexity

  • Runtime: O(N), where N = s.length.
  • Extra space: O(1).

Conclusion

There is a lot of solutions to this simple problem.

In order to improve the performance of your solution, you might need to know how to make use of the information, the constraints of the problem and the features the programming language supports.

Finally, having some mathematical knowledge always helps. That you can see with the one-line solution of Solution 5, where Modern C++ meets Mathematics.