Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

389. Find the Difference 🌟

You are given two strings s and t.

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

Return the letter that was added to t.

Brute force

sorting

Code

class Solution {
public:
    char findTheDifference(string s, string t)
    {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        int n = s.size();
        for (int i = 0; i < n; i++) {
            if (s[i] != t[i]) return t[i];
        }
        return t[n];
    }
};

Hashing

Code

class Solution {
public:
    char findTheDifference(string s, string t)
    {
        unordered_map<char, int> mp;
        for (auto x : s) mp[x]++;
        for (auto x : t) mp[x]--;
        for (auto x : mp) {
            if (x.second < 0) return x.first;
        }
        return 'a';
    }
};

Bit Manipulation

Code

class Solution {
public:
    char findTheDifference(string s, string t)
    {
        char res = 0;
        for (auto x : s) res ^= x;
        for (auto x : t) res ^= x;
        return res;
    }
};