HomeLeetcode242. Valid Anagram - Leetcode Solutions

242. Valid Anagram – Leetcode Solutions

Description:

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Examples:

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Solution in Python:

Python
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # If the lengths of the strings are different, they can't be anagrams
        if len(s) != len(t):
            return False
        
        # Create dictionaries to count the occurrences of each character in both strings
        count_s = {}
        count_t = {}
        
        # Count the characters in the first string
        for char in s:
            if char in count_s:
                count_s[char] += 1
            else:
                count_s[char] = 1
        
        # Count the characters in the second string
        for char in t:
            if char in count_t:
                count_t[char] += 1
            else:
                count_t[char] = 1
        
        # Compare the two dictionaries; if they are equal, the strings are anagrams
        return count_s == count_t

# Example usage:
solution = Solution()
print(solution.isAnagram("anagram", "nagaram"))  # Output: True
print(solution.isAnagram("rat", "car"))          # Output: False

Explanation:

  1. Length Check: First, we check if the lengths of the strings s and t are the same. If they are not, the strings cannot be anagrams, and we return False.
  2. Count Characters: We use dictionaries (count_s and count_t) to count the occurrences of each character in both strings.
    • For each character in s, we increase its count in count_s.
    • For each character in t, we increase its count in count_t.
  3. Compare Dictionaries: Finally, we compare the two dictionaries. If they are equal, it means both strings have the same characters with the same frequencies, hence they are anagrams, so we return True. Otherwise, we return False.

Solution in Javascript:

JavaScript
var isAnagram = function(s, t) {
    // If the lengths of the strings are different, they can't be anagrams
    if (s.length !== t.length) {
        return false;
    }

    // Create objects to count the occurrences of each character in both strings
    let countS = {};
    let countT = {};

    // Count the characters in the first string
    for (let char of s) {
        if (countS[char]) {
            countS[char]++;
        } else {
            countS[char] = 1;
        }
    }

    // Count the characters in the second string
    for (let char of t) {
        if (countT[char]) {
            countT[char]++;
        } else {
            countT[char] = 1;
        }
    }

    // Compare the two objects; if they are equal, the strings are anagrams
    for (let key in countS) {
        if (countS[key] !== countT[key]) {
            return false;
        }
    }

    return true;
};

// Example usage:
console.log(isAnagram("anagram", "nagaram")); // Output: true
console.log(isAnagram("rat", "car"));         // Output: false

Solution in Java:

Java
import java.util.HashMap;

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

        // Create HashMaps to count the occurrences of each character in both strings
        HashMap<Character, Integer> countS = new HashMap<>();
        HashMap<Character, Integer> countT = new HashMap<>();

        // Count the characters in the first string
        for (char charS : s.toCharArray()) {
            countS.put(charS, countS.getOrDefault(charS, 0) + 1);
        }

        // Count the characters in the second string
        for (char charT : t.toCharArray()) {
            countT.put(charT, countT.getOrDefault(charT, 0) + 1);
        }

        // Compare the two HashMaps; if they are equal, the strings are anagrams
        return countS.equals(countT);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.isAnagram("anagram", "nagaram")); // Output: true
        System.out.println(solution.isAnagram("rat", "car"));         // Output: false
    }
}

Solution in C#:

C#
using System;
using System.Collections.Generic;

public class Solution {
    public bool IsAnagram(string s, string t) {
        // If the lengths of the strings are different, they can't be anagrams
        if (s.Length != t.Length) {
            return false;
        }

        // Create dictionaries to count the occurrences of each character in both strings
        Dictionary<char, int> countS = new Dictionary<char, int>();
        Dictionary<char, int> countT = new Dictionary<char, int>();

        // Count the characters in the first string
        foreach (char charS in s) {
            if (countS.ContainsKey(charS)) {
                countS[charS]++;
            } else {
                countS[charS] = 1;
            }
        }

        // Count the characters in the second string
        foreach (char charT in t) {
            if (countT.ContainsKey(charT)) {
                countT[charT]++;
            } else {
                countT[charT] = 1;
            }
        }

        // Compare the two dictionaries; if they are equal, the strings are anagrams
        foreach (var kvp in countS) {
            if (!countT.ContainsKey(kvp.Key) || countT[kvp.Key] != kvp.Value) {
                return false;
            }
        }

        return true;
    }

}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular