L242. Valid Anagram

Problem:

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

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

Example 2:

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

Note: You may assume the string contains only lowercase alphabets.

t is a part of s.

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

Solution:

  • we could first increment the counter for s, then decrement the counter for t. If at any point the counter drops below zero, we know that t contains an extra letter not in s and return false immediately.

public boolean isAnagram(String s, String t) {
    if(s == null && t == null) return true;
    if(s == null && t == null) return false;
    if(s.length() != t.length()) return false;
     
    int[] freq = new int[26];
    for(int i =0; i < s.length(); i++){
        int pos = s.charAt(i) - 'a';
        freq[pos] += 1;
    }
    for(int j = 0; j < t.length(); j++){
        int pos = t.charAt(j) - 'a';
        freq[pos] -= 1;
    }
    for(int i : freq){
        if(i != 0) return false;
    }
    return true;    
}

Last updated

Was this helpful?