Strings Easy
Valid Anagram: Solution and Approach
Return true if string t is an anagram of string s, meaning both use exactly the same letters the same number of times.
Similar questions reported in: TCS, Wipro, Accenture, Capgemini, Cognizant
Example
- Input:
- s = "anagram", t = "nagaram"
- Output:
- true
Brute force first
Sort both strings and compare them. This is O(n log n).
The better idea
Count the letters. Add 1 for each letter in s and subtract 1 for each letter in t. If every count ends at 0, the strings are anagrams.
Steps
- If the lengths differ, return false.
- Make an array of 26 counts (for lowercase letters a to z).
- For each index i: count[s[i]] += 1 and count[t[i]] -= 1.
- Return true only if every count is 0.
Code
def is_anagram(s, t):
if len(s) != len(t):
return False
count = [0] * 26
for a, b in zip(s, t):
count[ord(a) - ord("a")] += 1
count[ord(b) - ord("a")] -= 1
return all(c == 0 for c in count)public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) {
if (c != 0) return false;
}
return true;
}Complexity
Time: O(n)
Space: O(1): the array always has 26 slots.
Edge cases to test
- Different lengths: return false right away.
- For Unicode input, use a hash map instead of a 26-slot array.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.