Video in progress

How do you check whether two words are anagrams of each other?

Count how many times each letter occurs, and if the two words give the same counts, they are anagrams. If it's only lowercase Latin letters, an int[] with 26 cells is enough, and time is O(n). Sorting and comparing works too, but it's O(n log n).

📖 Answer

"listen" and "silent" are anagrams: the same letters in a different order.

static boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        count[s.charAt(i) - 'a']++;
        count[t.charAt(i) - 'a']--;
    }
    for (int c : count) if (c != 0) return false;
    return true;
}

In a single array we add for one word and subtract for the other, and at the end everything must be zero. If the lengths differ, we return false right away.

If the alphabet isn't limited (Cyrillic, uppercase letters, digits), use a HashMap<Character, Integer> instead of int[26]. It's slower, but it handles any character.

An alternative solution: turn both strings into char[] with toCharArray(), sort them with Arrays.sort and compare them with Arrays.equals. The code is shorter, but slower.