Faced this question in an interview, which basically stated
Find if the given two strings are anagrams of each other in
O(N)
time without any extra space
I tried the usual solutions:
- Using a character frequency count (
O(N)
time,O(26)
space) (as a variation, iterating 26 times to calculate frequency of each character as well) - Sorting both strings and comparing (
O(NlogN)
time, constant space)
But the interviewer wanted a "better" approach. At the extreme end of the interview, he hinted at "XOR" for the question. Not sure how that works, since "aa" XOR "bb"
should also be zero without being anagrams.
Long story short, are the given constraints possible? If so, what would be the algorithm?