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 {string} str - Input string
* @returns {string|null} - First non-repeating character or null
*/
function firstNonRepeatingChar(str) {
// Create frequency map
const charCount = new Map();
// First pass: count frequencies
for (const char of str) {
charCount.set(char, (charCount.get(char) || 0) + 1);
}
// Second pass: find first char with count 1
for (const char of str) {
if (charCount.get(char) === 1) {
return char;
}
}
return null;
}
/**
* Group anagrams together from an array of strings
* @param {string[]} strs - Array of strings
* @returns {string[][]} - Groups of anagrams
*/
function groupAnagrams(strs) {
const anagramGroups = new Map();
for (const str of strs) {
// Sort characters to get a unique key for each anagram group
const sortedStr = str.split('').sort().join('');
// Create or add to an existing group
if (!anagramGroups.has(sortedStr)) {
anagramGroups.set(sortedStr, []);
}
anagramGroups.get(sortedStr).push(str);
}
// Return the groups as an array of arrays
return Array.from(anagramGroups.values());
}
// Example 1
groupAnagrams(["eat","tea","tan","ate","nat","bat"])
// Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
// Example 2
groupAnagrams([""])
// Output: [[""]]
// Example 3
groupAnagrams(["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 {number[]} nums
* @param {number} target
* @return {number[]}
*/
function twoSum(nums, target) {
// Your code here
}
// 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: