Valid Anagram
LeetCode 242 | Difficulty: Easyβ
EasyProblem Descriptionβ
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 * 10^4`
- `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?
Topics: Hash Table, String, Sorting
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Sortingβ
Sort the input to bring related elements together or enable binary search. Consider: does sorting preserve the answer? What property does sorting give us?
Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.
Solutionsβ
Solution 1: C# (Best: 148 ms)β
| Metric | Value |
|---|---|
| Runtime | 148 ms |
| Memory | N/A |
| Date | 2018-04-14 |
public class Solution {
public bool IsAnagram(string s, string t) {
Dictionary<char, int> oc = new Dictionary<char, int>();
int m=s.Length, n = t.Length;
if(m!=n) return false;
for (int i = 0; i < m; i++)
{
if(oc.ContainsKey(s[i])){
oc[s[i]]++;
}
else
{
oc.Add(s[i], 1);
}
}
for (int j = 0; j < n; j++)
{
if(!oc.ContainsKey(t[j]))
return false;
if(oc[t[j]]==0) return false;
oc[t[j]]--;
}
return true;
}
}
π 1 more C# submission(s)
Submission (2018-04-14) β 160 ms, N/Aβ
public class Solution {
public bool IsAnagram(string s, string t) {
char[] sArr = s.ToCharArray();
char[] tArr = t.ToCharArray();
Array.Sort(sArr);
Array.Sort(tArr);
return new String(sArr).Equals(new string(tArr));
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Hash map gives O(1) lookup β think about what to use as key vs value.