LeetCode #389 Find the Difference Solution & Explanation

LeetCode Problem

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.


Solution

When I first looked at the question, I immediately realized that using a dictionary to solve it would be a good idea. The keys correspond to characters, while the values represent their frequencies.

C# Solution

Solution1

public class Solution {
    public char FindTheDifference(string s, string t) {
        
        Dictionary<char,int> dict =   new Dictionary<char,int>();

        //1.count number of occurrences of each value
        foreach(var tmp in s)
        {
            if (!dict.ContainsKey(tmp))
            {
                dict.Add(tmp, 1);
            }
            else
            {
                dict[tmp] = dict[tmp]+1;
            }
        }

        //2. find the added char
        foreach(var tmp in t){
            if (!dict.ContainsKey(tmp)){
                return tmp;
            }
            var num = dict[tmp]-1;
            if(num<0){
                return tmp;
            }
            dict[tmp] = num;
        }

        return '\0';    // Default value used to ensure every possible code path returns a value.
    }
}

If we can’t find the char in the dictionary or its appearance count is not enough, we will return the char.

Java Solution

Solution1

class Solution {
    public char findTheDifference(String s, String t) {
        Map<Character, Integer> dict =  new HashMap<Character, Integer>();

        //1.count number of occurrences of each value
        for (char tmp: s.toCharArray()) 
        {
            if (!dict.containsKey(tmp))
            {
                dict.put(tmp, 1);
            }
            else
            {
                dict.put(tmp, dict.get(tmp)+1);
            }
        }

        //2. find the added char
        for (char tmp: t.toCharArray()) {
            if (!dict.containsKey(tmp)){
                return tmp;
            }
            int num = dict.get(tmp)-1;
            if(num<0){
                return tmp;
            }
            dict.put(tmp,num);
        }

        return '\0';    // Default value used to ensure every possible code path returns a value.
    }
}

uh… that’s too slow, maybe we need to find another way… (just faster than 20%)


Conclusion

We will be back, with faster code…

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link: Find the Difference – LeetCode

Similar Questions

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *