Valid Anagram

Asked atAdobe
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

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.

Input : s = "anagram" , t = "nagaram" Output : true Explanation : We can rearrange the characters of string s to get string t as frequency of all characters from both strings is same.

Input : s = "dog" , t = "cat" Output : false Explanation : We cannot rearrange the characters of string s to get string t as frequency of all characters from both strings is not same.

Input : s = "eat" , t = "tea"

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

cpp

class Solution{	
	public:
		bool anagramStrings(string& s,string t){
			//your code goes here
		}
};

java

class Solution {  
    public boolean anagramStrings(String s, String t) {
        //your code goes here
    }
}

python

class Solution:    
    def anagramStrings(self, s, t):
        #your code goes here

javascript

class Solution {
    anagramStrings(s, t) {
        //your code goes here
    }
}

csharp

class Solution
{
    public bool anagramStrings(string s, string t)
    {
        //your code goes here
    }
}

go

func anagramStrings(s string, t string) bool {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Return false immediately if lengths differ.
  2. 02Count characters in the first string.
  3. 03Subtract counts while scanning the second string.
  4. 04Verify no count becomes invalid and all counts finish at zero.

Reference answer

Then expect these follow-ups

  • How would you group a list of anagrams?

    Tests: hashing

  • How does Unicode normalization affect anagram checks?

    Tests: text handling

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question