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.

My Solution

We can do this by finding the counts of the characters in both s and t. Then we iterate through all lowercase characters and if the counts of a character in s differs from that in t, we return that character.

Time complexity would be O(m+n) because we do one pass through s and one pass through t. Space complexity is O(1) because there are only a constant 26 characters that we need to keep counts for.

class Solution {
    public char findTheDifference(String s, String t) {
        int[] counts_s = new int[26];
        int[] counts_t = new int[26];

        for (char c : s.toCharArray()) {
            counts_s[c-'a']++;
        }

        for (char c : t.toCharArray()) {
            counts_t[c-'a']++;
        }

        for (int i = 0; i < 26; i++) {
            if (counts_s[i] != counts_t[i]) {
                return (char)('a'+i);
            }
        }

        return 'a';
    }
}
Previous
Previous

Is Subsequence

Next
Next

First Unique Character in a String