Anagram and Palindrome
Anagram and palindrome problems are common in interviews. They test your ability to count characters and compare strings efficiently.
1. Check if Two Strings are Anagrams
Anagrams have the same character counts. Use a frequency array (size 26 for lowercase letters).
public static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
int[] freq = new int[26];
for (int i = 0; i < s1.length(); i++) {
freq[s1.charAt(i) - 'a']++;
freq[s2.charAt(i) - 'a']--;
}
for (int count : freq) {
if (count != 0) return false;
}
return true;
}
2. Group Anagrams
Given a list of strings, group anagrams together. Use a map where the key is a sorted string or a character count string.
public static List> groupAnagrams(String[] strs) {
Map> map = new HashMap<>();
for (String s : strs) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
String key = new String(arr);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}
3. Palindrome Check
Already covered in string manipulation. For sentences, ignore non-alphanumeric and case.
Two Minute Drill
- Anagram check: use frequency array or sort strings.
- Group anagrams: use map with sorted string as key.
- Palindrome check: two-pointer from ends, ignoring non-alphanumeric.
- These problems test character frequency and string comparison skills.
Need more clarification?
Drop us an email at career@quipoinfotech.com
