Simple Java solution. O(N) runtime, O(1) memory, runs in 9ms.


  • 0
    T
    public class Solution {
        public char findTheDifference(String s, String t) {
            // count[x] = the total occurrences of character 'x' in string 's'
            int[] count = new int[26];
            
            for(int i=0; i < s.length(); i++) {
                char ch = s.charAt(i);
                count[ch - 'a']++;
            }
            
            for(int i=0; i < t.length(); i++) {
                char ch = t.charAt(i);
                
                // Check if the current 'ch' occurs more in string 't' than in string 's' 
                if(count[ch - 'a'] == 0) return ch; // if so, return the current string immediately
                count[ch - 'a']--;
            }
            
            return '!'; // just a dummy value so that the code compiles
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.