LC #242: Valid Anagrams

๐ง Problem Statement
Given two strings
s
andt
, returntrue
ift
is an anagram ofs
, andfalse
otherwise.
An anagram uses the same characters and the same frequency, but in any order.
๐ Leetcode Link
๐ฅ Brute Force
// generate all permutations of s and check if t exists in it
List<String> perms = generatePermutations(s);
return perms.contains(t);
- Time: O(n!) โ factorial due to permutations
- Space: O(n) or more
โ Not scalable. Just a theoretical baseline.
โก Optimized: Frequency Count using Array
int[] freqArr = new int[26]; // fixed-size array for lowercase aโz (O(1) space)
for (char c : s.toCharArray()) // count frequency of each char in s
freqArr[c - 'a']++;
for (char c : t.toCharArray()) { // decrement frequency for each char in t
if (freqArr[c - 'a'] < 1) return false; // char not present or used too many times
freqArr[c - 'a']--;
}
for (int count : freqArr) // final check: all frequencies must be zero
if (count != 0) return false;
return true; // all matched โ valid anagram
- Time: O(n) โ traverse both strings once
- Space: O(1) โ uses 26-sized array for lowercase chars
โ Simple. Fast. Most interviewer-friendly.
๐ง Key Insights
- Anagram = same characters + same frequencies (order doesn't matter)
- Sorting approach works too (
Arrays.sort
) but is slower โ O(n log n) - Better to count character frequencies โ O(n)
- Initially considered 2 HashMaps โ works but not optimal
- Use 1 array or 1 HashMap instead โ cleaner + space-efficient
- If using array, final check = all values must be 0
โ For lowercase only:
int[] freq = new int[26]; index = c - 'a';
โ For alphanumeric (AโZ, aโz, 0โ9):
Total possible chars = 62if (Character.isUpperCase(c)) index = c - 'A'; // 0โ25 else if (Character.isLowerCase(c)) index = c - 'a' + 26; // 26โ51 else index = c - '0' + 52; // 52โ61
๐ For arbitrary Unicode (e.g., emojis, symbols):
UseHashMap<Character, Integer>
for dynamic char support
โช You lose O(1) space, but gain generality
๐งช Dry Run + Test Cases
โ Test Case 1
Input: s = "aabb", t = "baba"
Steps:
- Count
s
: a+2, b+2 โ freq = [2a, 2b] - Use
t
: bโ1, aโ1, bโ1, aโ1 โ all counts zero
โ Final freq array = all zeros โ returntrue
โ Test Case 2
Input: s = "rat", t = "car"
Steps:
- Count
s
: r+1, a+1, t+1 - Use
t
: c not in freq โ returnfalse
โ Extra char โ not an anagram
โ ๏ธ Edge Case 1
Input: s = "", t = ""
Steps:
- Both strings empty โ no characters to mismatch
โ returntrue
(by definition)
โ ๏ธ Edge Case 2
Input: s = "a", t = ""
Steps:
- Count
s
: a+1 t
is empty โ never decrements
โ leftover a in freq โ returnfalse
๐ Similar Problems
Group Anagrams โ LC #49
โช Group words that are anagrams โ use a HashMap with sorted string or char count as keyFind All Anagrams in a String โ LC #438
โช Sliding window + freq count โ find all substrings that are anagrams of a given patternValid Palindrome โ LC #125
โช Normalize and compare โ similar pre-processing and cleanup logicRansom Note โ LC #383
โช Use char counts to check if one string can construct anotherLongest Palindrome โ LC #409
โช Use frequency counting to maximize palindrome length
Subscribe to my newsletter
Read articles from LilSardarX directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

LilSardarX
LilSardarX
Iโm figuring things out in tech โ and blogging along the way. I write what I learn, so I can revise it later and maybe help you avoid a few rabbit holes.