Learn how to solve common hash table problems including finding non-repeating characters and grouping elements by computed values.
/**
* Find the first non-repeating character in a string
* @param str Input string
* @return First non-repeating character or null
*/
public static Character firstNonRepeatingChar(String str) {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (char c : str.toCharArray()) {
if (charCount.get(c) == 1) {
return c;
}
}
return null;
}
/**
* Group anagrams together from an array of strings
* @param strs Array of strings
* @return Groups of anagrams
*/
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> anagramGroups = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedStr = new String(chars);
anagramGroups.computeIfAbsent(sortedStr, k -> new ArrayList<>()).add(str);
}
return new ArrayList<>(anagramGroups.values());
}
// Example 1
System.out.println(groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"}));
// Output: [[eat, tea, ate], [tan, nat], [bat]]
// Example 2
System.out.println(groupAnagrams(new String[]{""}));
// Output: [[""]]
// Example 3
System.out.println(groupAnagrams(new String[]{"a"}));
// Output: [[a]]
Now that you've learned about hash tables for frequency counting and grouping, try these practice challenges to reinforce your understanding.
Given an array of integers nums
and an integer target
,
return the indices of the two numbers such that they add up to target
.
/**
* @param nums
* @param target
* @return indices of the two numbers such that they add up to target
*/
public static int[] twoSum(int[] nums, int target) {
// Your code here
return new int[]{};
}
// Example 1
twoSum([2, 7, 11, 15], 9)
// Output: [0, 1] (because nums[0] + nums[1] = 2 + 7 = 9)
// Example 2
twoSum([3, 2, 4], 6)
// Output: [1, 2]
// Example 3
twoSum([3, 3], 6)
// Output: [0, 1]
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
function isAnagram(s, t) {
// Your code here
}
If you want more practice with hash tables, check out these LeetCode problems: