Valid Anagram

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

 

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.

My Solution

We keep counts of every lowercase character in s and t. Then we iterate through all possible characters and check that the count for each character is the same between s and t.

Time complexity is O(m+n), where m is the length of s and n is the length of t, to generate the counts array. It’s then constant time to iterate through every possible character and compare the counts, since there are a constant 26 possible characters. Space complexity is O(1) to maintain the counts array for s and t since they contain a constant number of characters.

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] s_counts = new int[26];
        int[] t_counts = new int[26];

        for (char c : s.toCharArray()) {
            s_counts[c-'a']++;
        }

        for (char c : t.toCharArray()) {
            t_counts[c-'a']++;
        }

        for (int i = 0; i < 26; i++) {
            if (s_counts[i] != t_counts[i]) {
                return false;
            }
        }

        return true;
    }
}
Previous
Previous

Binary Tree Paths

Next
Next

Palindrome Linked List