C++ O(N) algorithm


  • 0
    A
    char findTheDifference(string s, string t){
    
           	int chars[26] = {0}; // we know string will be in lower alphabets
    
    	for(int i=0; i<t.length();i++){
    
                chars[t[i]-'a']++; // increment character count
    
                if(s[i]-'a' >= 0) // if character exists in 's' then decrement
    		 chars[s[i]-'a']--;
    	}
    		
    	for(int i=0; i<26;i++){
    
    	    if(chars[i] == 1){
    		return  i+'a'; // form additional character
    	    }
    	}
    		
    	return 0;
    		
    }
    

Log in to reply
 

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