Skip to content

Instantly share code, notes, and snippets.

@miniharryc
Created December 16, 2019 16:37
Show Gist options
  • Save miniharryc/9c77553bca351a4c01f619911121744e to your computer and use it in GitHub Desktop.
Save miniharryc/9c77553bca351a4c01f619911121744e to your computer and use it in GitHub Desktop.
An O(n) solution to anagrams in constant space using XOR
boolean isAnagram( String s1, String s2) {
if (s1.length() != s2.length()) return false;
int x = 0;
for (int i = 0; i<s1.length(); i++) {
x ^= s1.charAt(i) ^ s2.charAt(i);
}
return x == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment