Given two strings s
and t
, write a function to determine if t
is an anagram of s
.
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.
To determine if two strings are anagrams:
Let’s implement this in Java.
import java.util.HashMap;
import java.util.Map;
public class Solution {
public boolean isAnagram(String s, String t) {
// If lengths are different, they cannot be anagrams
if (s.length() != t.length()) {
return false;
}
// HashMap to count frequency of each character
Map<Character, Integer> charCountMap = new HashMap<>();
// Count characters in string s
for (char c : s.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Reduce count based on string t
for (char c : t.toCharArray()) {
if (!charCountMap.containsKey(c)) {
return false;
}
charCountMap.put(c, charCountMap.get(c) - 1);
if (charCountMap.get(c) == 0) {
charCountMap.remove(c);
}
}
// If map is empty, all characters perfectly matched
return charCountMap.isEmpty();
}
}
false
.HashMap
to store the frequency of each character in string s
.t
: Loop through string t
and decrease the frequency count in the map. If a character is not found or its count goes negative, they are not anagrams.true
. Otherwise, return false
.This solution ensures that we are checking both strings in linear time and using space proportional to the number of unique characters, making it efficient for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?