Skip to content

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.

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:

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

        for (int i = 0; i < s.length(); i++){
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
        }

        for (int i = 0; i < t.length(); i++){
            char cur = t.charAt(i);
            if (!map.containsKey(cur)){
                return cur;
            }else{
                int count = map.get(cur);
                if (count == 0){
                    return cur;
                }else{
                    map.put(cur, count - 1);
                }
            }
        }

        return t.charAt(0);
    }
}

// TC: O(n)
// SC: O(n)