The first soln comes to head is sorting them and checking if they are equal.
Takes O(N log N ) complexity.
To make it work in O(N) I know two procedures,
1, Assign a prime number to each & every char. Multiply the prime numbers.
if result is same for both, then they are anagrams. But if the length is more then it overflows.
2, create a char array. For the first string
for(i = 1 to N )
do
char_array[a[i]]++;
for sencond array
for(i = 1 to N )
do
char_array[b[i]]--;
Now check if entire array is zeroes. If yes, those are anagrams.
No comments:
Post a Comment