My O(n) solution using array as hash

  • 0

    I am using one array of length 26 (assuming all characters are small case alphabets). First loops establishes the count of each letter in string 's' and second loop decrement the count by one. Finally strings are anagram only when the array contains all zero. This runs in O(n) time.

    bool isAnagram(string s, string t) {
    	int ar[26] = {0};
    	for(int i=0; i<s.size(); i++)
    	for(int i=0; i<t.size(); i++)
    	for(int i=0; i<26; i++)
    		if(ar[i] != 0)
    			return false;
    	return true;      

Log in to reply

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