Learn how to solve common hash table problems including finding non-repeating characters and grouping elements by computed values.
def first_non_repeating_char(s):
# Create frequency map
char_count = {}
# First pass: count frequencies
for char in s:
char_count[char] = char_count.get(char, 0) + 1
# Second pass: find first char with count 1
for char in s:
if char_count[char] == 1:
return char
return None
def group_anagrams(strs):
from collections import defaultdict
anagram_groups = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
anagram_groups[key].append(s)
return list(anagram_groups.values())
# Example 1
print(group_anagrams(["eat","tea","tan","ate","nat","bat"]))
# Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
# Example 2
print(group_anagrams([""]))
# Output: [[""]]
# Example 3
print(group_anagrams(["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
.
def two_sum(nums, target):
# Your code here
pass
// 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.
def is_anagram(s, t):
# Your code here
pass
If you want more practice with hash tables, check out these LeetCode problems: