Skip to content

Instantly share code, notes, and snippets.

@gurbuzali
Created May 1, 2021 22:03
Show Gist options
  • Save gurbuzali/b25c62edc42e4ec42fc0683c6cae67b9 to your computer and use it in GitHub Desktop.
Save gurbuzali/b25c62edc42e4ec42fc0683c6cae67b9 to your computer and use it in GitHub Desktop.
public class IsAnagram {
boolean anagram(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
int[] counts = new int[26];
for(int i=0; i<s1.length(); i++) {
//'a' - 'a' -> 0, 'b' - 'a' -> 1 ....
counts[s1.charAt(i)-'a']++;
}
for(int i=0; i<s1.length(); i++) {
counts[s2.charAt(i)-'a']--;
if(counts[s2.charAt(i)-'a'] < 0)) {
return false;
}
}
return true;
}
}
@gurbuzali
Copy link
Author

m = s1#length
n = s2#length
Time complexity O(m+n)
space complexity O(1), fixed size int[]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment