Problem:
=============
given two string with equal length, tell whether they are anagram.
Naive Solution : (Time complexity = O(n2) )
==============
1. initiate two loops and match every letter of the first string with every letter of second string
2. when you find one such matched character, flag them both as checked
3. move on with your next computations, until At some point of time before the end of first string , you come across a mismatch (that you don't get a pair for one of the characters ) then return false straight away.
4. return true
Solution 2 : (Time complexity = O(n) )
===============
1. Assuming your string to consist of only one cased of characters (say lower case or upper case) initialize an array say int counter[26] and initialize all values to 0 assume a variable "index_help" which is 65 (for upper cased) and 97(for lower cased). otherwise, initialize the int counter[52], to include both upper and lower cased.
2. Traverse through the string1 as:
for i in loop from 0 to string length of str1
count[ string1[i] - index_help ]++;
3. After this you'll have exact count of characters in string1.Now through string2 as
for i in loop from 0 to string length of str2
count[ string2[i] - index_help ]--;
4. Finally if they are anagrams the count array after the above loops should hold 0's throughout else can return false.
Code:
===============
bool isAnagram(string str1, string str2)
{
int counter[52];
int upper_index = 65;//lower cased is 97
for (int i = 0; i < str1.length(); i++)
counter[str1.at(i) - upper_index]++;
for (int i = 0; i < str2.length(); i++)
counter[str2.at(i) - upper_index]--;
for (int i = 0; i < 52; i++)
if(counter[i]) return false;
return true;
}