Skip to content

242. Valid Anagram

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.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Solution:

class Solution {
    public boolean isAnagram(String s, String t) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();

        char[] chS = s.toCharArray();
        for (int i = 0; i < chS.length; i++){
            map.put(chS[i], map.getOrDefault(chS[i], 0) + 1);
        }

        char[] chT = t.toCharArray();
        for (int j = 0; j < chT.length; j++){
            if (!map.containsKey(chT[j]) || map.get(chT[j]) == 0){
                return false;
            }

            map.put(chT[j], map.get(chT[j]) - 1);
        }

        List<Integer> values = new ArrayList<Integer>(map.values());

        for (int i = 0; i < map.size(); i++){
            if (values.get(i) != 0){
                return false;
            }
        }

        return true;
    }
}

// TC: O(n)
// sC: O(n)
class Solution {
    public 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[s.charAt(i) - 'a'] + 1;
        }

        for (int i = 0; i < t.length(); i++){
            if (count[t.charAt(i) - 'a'] == 0){
                return false;
            }
            count[s.charAt(i) - 'a'] = count[s.charAt(i) - 'a'] - 1;
        }

        return true;
    }
}

// TC: O(n)
// SC: O(1)