Valid Anagram
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 herejavascript
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+
- 01Return false immediately if lengths differ.
- 02Count characters in the first string.
- 03Subtract counts while scanning the second string.
- 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