KatInterview

242. Valid Anagram

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once. The problem asks us to determine if string t is an anagram of string s. This essentially means we need to check if both strings are composed of the same characters with the same frequencies.

Solution

Valid Anagram in Python

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # If the lengths of the strings are different, they cannot be anagrams.
        if len(s) != len(t):
            return False

        # Create a list to store the frequency of each character.
        # Since the strings only contain lowercase English letters, a list of size 26 is sufficient.
        counts = [0] * 26

        # Iterate through both strings simultaneously.
        # Increment the count for characters in s and decrement for characters in t.
        for i in range(len(s)):
            counts[ord(s[i]) - ord('a')] += 1
            counts[ord(t[i]) - ord('a')] -= 1

        # If the strings are anagrams, all counts in the list should be zero.
        # Iterate through the counts list to check.
        for count in counts:
            if count != 0:
                return False
        
        # If all counts are zero, the strings are anagrams.
        return True

        # A more Pythonic but potentially less illustrative solution for interviews:
        # from collections import Counter
        # return Counter(s) == Counter(t)

Valid Anagram in Java

class Solution {
    public boolean isAnagram(String s, String t) {
        // If the lengths of the strings are different, they cannot be anagrams.
        if (s.length() != t.length()) {
            return false;
        }

        // Create an array to store the frequency of each character.
        // Since the strings only contain lowercase English letters, an array of size 26 is sufficient.
        int[] counts = new int[26];

        // Iterate through both strings simultaneously.
        // Increment the count for characters in s and decrement for characters in t.
        for (int i = 0; i < s.length(); i++) {
            counts[s.charAt(i) - 'a']++;
            counts[t.charAt(i) - 'a']--;
        }

        // If the strings are anagrams, all counts in the array should be zero.
        // Iterate through the counts array to check.
        for (int count : counts) {
            if (count != 0) {
                return false;
            }
        }

        // If all counts are zero, the strings are anagrams.
        return true;
    }
}

Valid Anagram in C++

class Solution {
public:
    bool isAnagram(string s, string t) {
        // If the lengths of the strings are different, they cannot be anagrams.
        if (s.length() != t.length()) {
            return false;
        }

        // Create an array to store the frequency of each character.
        // Since the strings only contain lowercase English letters, an array of size 26 is sufficient.
        int counts[26] = {0};

        // Iterate through both strings simultaneously.
        // Increment the count for characters in s and decrement for characters in t.
        for (int i = 0; i < s.length(); ++i) {
            counts[s[i] - 'a']++;
            counts[t[i] - 'a']--;
        }

        // If the strings are anagrams, all counts in the array should be zero.
        // Iterate through the counts array to check.
        for (int i = 0; i < 26; ++i) {
            if (counts[i] != 0) {
                return false;
            }
        }

        // If all counts are zero, the strings are anagrams.
        return true;
    }
};

Valid Anagram in TypeScript

function isAnagram(s: string, t: string): boolean {
    // If the lengths of the strings are different, they cannot be anagrams.
    if (s.length !== t.length) {
        return false;
    }

    // Create an array to store the frequency of each character.
    // Since the strings only contain lowercase English letters, an array of size 26 is sufficient.
    const counts = new Array(26).fill(0);
    const baseCharCode = 'a'.charCodeAt(0);

    // Iterate through both strings simultaneously.
    // Increment the count for characters in s and decrement for characters in t.
    for (let i = 0; i < s.length; i++) {
        counts[s.charCodeAt(i) - baseCharCode]++;
        counts[t.charCodeAt(i) - baseCharCode]--;
    }

    // If the strings are anagrams, all counts in the array should be zero.
    // Iterate through the counts array to check.
    for (const count of counts) {
        if (count !== 0) {
            return false;
        }
    }

    // If all counts are zero, the strings are anagrams.
    return true;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.